Input statements are the portion of a program that instructs a computer how to read and process information.
In Python 2 the following 2 functions are available to read dynamic input from the keyboard.
This function always reads the data from the keyboard in the form of String Format. We have to convert that string type to our required type by using the corresponding type casting methods.
x = raw_input("Enter First Number:") print(type(x)) ==> It will always print str type only for any input type
input() function can be used to read data directly in our required format.We are not required to perform type casting.
x = input("Enter Value) type(x) 100 ==> int "Waytoeasylearn" ==> str 10.5 ==> float True ==> bool
- But in Python 3 we have only input() method and raw_input() method is not available.
- Python3 input() function behavior exactly same as raw_input() method of Python2. i.e every input value is treated as str type only.
- raw_input() function of Python 2 is renamed as input() function in Python 3.
>>> type(input("Enter value:")) Enter value: 10 <class 'str'> Enter value: 10.5 <class 'str'> Enter value: True <class 'str'>
a = input("Enter First Number:") b = input("Enter Second Number:") i = int(a) j = int(b) print("The Sum:",i+j)
Enter First Number: 100 Enter Second Number: 200 The Sum: 300
Read multiple values from the keyboard
a, b = [int(x) for x in input("Enter 2 numbers :").split()] print("Product is :", a*b) Enter 2 numbers :100 2 Product is : 200
Here split() function can take space as separator by default .But we can pass anything as separator.
a,b,c = [float(x) for x in input("Enter 3 float numbers :").split(',')] print("The Sum is :", a+b+c) Enter 3 float numbers :10.5,20.6,20.1 The Sum is : 51.2
eval Function take a String and evaluate the Result.
x = eval(“10+20+30”) print(x) 60 x = eval(input(“Enter Expression”)) Enter Expression: 10+2*3/4 11.5
eval() can evaluate the Input to list, tuple, set, etc based the provided Input.