Python Input, Output and Import



Python offers several built-in functions that helps to interact with the code.

Some of the most used built-in functions are the input() and the print() functions. They are generally used for standard input and output operations.


Python Output Using Print Function

The print() function is one of the most used built-in functions in Python. The print() function is used to output data to the standard output (screen). It can also be used to output data to a file.

Syntax

The syntax of the print() function is as follows:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Parameter Values

  • *objects : Any object, and as many as you like. It will be converted to a string before printed.
  • sep='' : Optional. It indicates how to separate the objects. Default is ''.
  • end='\n' : Optional. It indicates what to print at the end. Default is \n.
  • file=sys.stdout : Optional. It is an object that specify where the output is printed. Default is sys.stdaut.
  • flush=False : Optional. It is a boolean that indicates if the output is flushed True or buffered False. Default is False.

Examples

Let us consider the following example:

# Printing a simple string
print("Hello World!")

x = 14

# Printing the value of x
print("The value is x is", x)

# Printing multiple values
print(1, 2, 3, 4, 5)

# Printing multiple values with a separator
print(1, 2, 3, 4, 5, sep='#')

# Printing multiple values with a separator and an end of line
print(1, 2, 3, 4, 5, sep='*', end='&')

After executing the above code, the output will be as follows:

Hello World!
The value is x is 14
1 2 3 4 5
1#2#3#4#5
1*2*3*4*5&

Python Output Formatting

To format the output and make it look nicer, you can use the str.format() function that works for any string object.

In the following example, we used the format function with the curly braces {} as placeholders.

a = 17
b = 20

print("The value of a is {} and the value of b is {}".format(a, b))

Output:

The value of a is 17 and the value of b is 20

You can also specify the order in which the variables are printed by using numbers.

print("I prefer {0} and {1}".format("apple", "kiwi"))
print("I prefer {1} and {0}".format("apple", "kiwi"))

After executing the above code, the output will be as follows:

I prefer apple and kiwi 
I prefer kiwi and apple

You can even use keyword arguments to format the string.

>>> print("Hi {name}, let us start learning {language}.".format(language = "Python", name = "Robert"))

Hi Robert, let us start learning Python.

Python also offers a way to format strings like the old sprintf() style used in the C programming language. To achieve this, we will use the % operator as follows:

>>> pi = 3.14159265359
>>> print("The value of Pi is %1.3f" %pi)
The value of Pi is 3.142
>>> print("The value of Pi is %1.5f" %pi)
The value of Pi is 3.14159

Python Input

An application often needs to interact with users, either to get data or to provide some result.

In Python, to take the user's input, you can use the input() function?

Syntax

The syntax for the input() function is as follows:

input([prompt])

Parameter Values

  • prompt : Optional. A string representing a default message before the input.

Examples

Let us consider the following example:

n = input("Enter a number: ")
print("The value of n is ", n)
print("The type of n is ", type(n))

Output:

Enter a number: 9 
The value of n is 9 
The type of n is <class 'str'>

As we can see above, the entered value 9 is interpreted by Python as a string, not a number. To convert the entered value into a number, you can use the int() or float() functions.

n = input("Enter a number: ")
print("The type of n is ", type(n))

n = int(n)
print("The type of n after int function is ", type(n))

n = float(n)
print("The type of n after float function is ", type(n))

Output:

Enter a number: 8
The type of n is  <class 'str'>
The type of n after int function is  <class 'int'>
The type of n after float function is  <class 'float'>

The same operation of converting string to a number can be done using the eval() function. The eval() function can even evaluate expressions passed as a string.

a = "4+6"
print(eval(a))

b = "4+6"
print(int(b))

Output:

10

ValueError Traceback (most recent call last)

      4 b = "4+6"
----> 5 print(int(b))

ValueError: invalid literal for int() with base 10: '4+6'

Python Import

When a program starts to be bigger, it is a good practice to break it into multiple modules.

In Python, a module is a file containing definitions and statements.

Python modules are defined by a file name and have the .py extension.

In Python, we use the import keyword to import definitions that are inside a module into another module.

In the following example, we import and use the math module.

import math

print(math.pi)

Output:

3.141592653589793

After importing the math module, all the definitions inside it are now available in our scope. You can also import some specific attributes and functions by using the from keyword.

>>> from math import pi
>>> pi
3.141592653589793

When we import a module, Python will search at several places defined in sys.path that contains a list of directory locations.

import sys

print(sys.path)

Output:

['', '/content', '/env/python', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/dist-packages', '/usr/lib/python3/dist-packages', '/usr/local/lib/python3.7/dist-packages/IPython/extensions', '/root/.ipython']


ExpectoCode is optimized for learning. Tutorials and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using this site, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 2020-2021 by ExpectoCode. All Rights Reserved.