Python Input/Output

This tutorial has explained the Python’s built-in function input() and print() for input and output operation respectively.

Python Input

Software program often needs user input from the keyboard. Python provides the input() function to allow this task. input() function pause the execution until the user press the Enter key.

Syntax:

input(prompt)
Where,

prompt: A String, representing a default message before the input.

Example:

fname = input('Enter your First Name:')
lname = input('Enter your Last Name:')
print('Hello, {} {}'.format(fname,lname))

Output:

Enter your First Name:Alex
Enter your Last Name:zuck
Hello, Alex zuck

Python’s input() function always returns a string. If you want a numeric value, then you need to apply type casting to convert the input string to the required data type.

Example

a = input('Enter your the value of a:')
b = 10
sum = a+b
print("sum is :",sum)

Output:

Enter your the value of a:23
Traceback (most recent call last):
  File "arg.py", line 3, in <module>
    sum = a+b
TypeError: must be str, not int

Here, the data type of the variable a is string by default. Python won’t allow the addition operation with string. Hence, it is required to convert the input string to integer or float.

a = int(input('Enter your the value of a:'))
b = 10
sum = a+b
print("sum is :",sum)

Output:

Enter your the value of a:23
sum is : 33

.     .     .

Python Output

Software program often needs to present the information back to the user. The information can be printed in a human-readable form to screen or written to a file. There are several ways to present the output of a program. Python provides the print() function to print the data to screen.

In [1]:
print("Good, Morning")
print("How are you?")
Out[1]:
Good, Morning
How are you?

We can also print the output using Python’s sys package.

In [2]:
import sys
sys.stdout.write("Hello, World")
Out[2]:
Hello, World

Arguments in Print()

We can also provide the arguments to the print() function to control the format of the output.

    • The sep= argument: Objects are separated by sep value. Default value: ' '
    • The end= argument: It printed the end value at last.
    • file – Default:sys.stdout will be used which prints objects on the screen.
    • flush – Default value: False. If True, the stream is forcibly flushed.

 

Examples:

In [3]:
name = "Mark"
print("Hello,",name)
Out[3]:
Hello, Mark
In [4]:
name = "Mark"
print("Hello",name,"How are you?",sep="#")
Out[4]:
Hello#Mark#How are you?
In [5]: 
name = "Mark" 
print("Hello",name,"How are you?",sep="...") 
Out[5]: 
Hello...Mark...How are you? 
In [6]:
name = "Mark"
print("Hello",name,"How are you?",end="@@")
Out[6]:
Hello Mark How are you?@@

.     .     .

Leave a Reply

Your email address will not be published. Required fields are marked *

Python Tutorials