input():
- The input() from the user it takes evaluates the expression.
- In Python automatically identifies whether user entered a string or a number or list.
- If the input provided is not correct then automatically coming syntax error or exception is raised by python.
Example:
val = input("Enter your value: ")
print(val)
How it works?
- input() function keep on reading the input until end user strikes enter key.
- the input value will be collected into assigned variable left side.
- It is optional to display the every input on screen.
Example:
print('Enter your name:')
x = input()
print('Hello, ' + x)
- input() function takes the input values in String format.
- We must typecast(convert) the string type into specific type before its use.
- We can check the type of input using type() method.
Code:
print("Enter an integer :")
x = input()
print("Enter String :")
y = input()
print("Enter float :")
z = input()
print("x type :", type(x))
print("y type :", type(y))
print("z type :", type(z))
Output:
Enter an integer :
10
Enter String :
naresh
Enter float :
23.4
x type : <class 'str'>
y type : <class 'str'>
z type : <class 'str'>
We convert pre-define type conversion methods to convert the input type.
print("Enter an integer :")
x = int(input())
print("Enter String :")
y = input()
print("Enter float :")
z = float(input())
print("x type :", type(x))
print("y type :", type(y))
print("z type :", type(z))
Output:
Enter an integer :
10
Enter String :
naresh
Enter float :
23.45
x type : <class 'int'>
y type : <class 'str'>
z type : <class 'float'>