Read Input in Python
Python input and output functions are very important for reading and writing data. print function usage is given in this article, Printing in Python using Print() function.
Reading data or values from user or console is essential in day to day programming.
So, what is the function used in python to read input data?
Answer is input() function.
Ex:
# Following line takes the input from user var=input() #Deafult value is String
If you want to ask for required input from user with a statement, you can also write as
var=input('Enter your Name:') #Above line prints Enter your Name: on the console # Name will be assigned to var
print the name with Hello message to the console
print("Hello", var) #it prints Hello Name
if you want to read an integer from user, just wrap input statement in a datatype.
# Store two integer input numbers num1 = int(input('Enter first number: ')) num2 = int(input('Enter second number: '))
by default, the input function takes String value as an input. We are converting String value to integer value as int(input())
Let us see an example program for addition of two numbers
# Python code to add two integer numbers # Store two integer input numbers num1 = int(input('Enter first number: ')) num2 = int(input('Enter second number: ')) # Add num1 and num2 values sum = num1 + num2 # Print output print('Total sum of {0} and {1} is {2}' .format(num1, num2, sum))
output for addition of numbers:
Enter first number: 10 Enter second number: 20 Total sum of 10 and 20 is 30
Python program for addition of two floating point numbers is also similar to the above program, but we need to use float in the place of int.
# Python code to add two floating point numbers # Store two float input numbers num1 = float(input('Enter first number: ')) num2 = float(input('Enter second number: ')) # Add num1 and num2 values sum = num1 + num2 # Print output print('Total sum of {0} and {1} is {2}' .format(num1, num2, sum))
output for the above code
Enter first number: 20.56 Enter second number: 15.23 Total sum of 20.56 and 15.23 is 35.79
for more programs visit the programs section Python Codes