In this Python tutorial, we will study that how to take input in Python from user through keyboard.
Taking input from user in Python is very easy as compared to other programming languages.
How to take input in Python
Using input keyword, we can take input from user, and can do whatever we want to do with that input data.
Example
Let’s understand it by taking example
data=input("Enter some data:") print("value you enter is:", data)
Output
Enter some data: learn Python
value you enter is: learn Python
Explanation: When we run above example, In the command prompt it will ask some data to be enter. When we enter some value, program take that value to process it.
Point to remember: In Python, by default Python will take any data as a string, if you enter numeric data, then also it treats it as string data. Let’s see this by taking example.
data=input("Enter some data:") print("value you enter is:", data) print("data type of ",data, "is:", type(data))
Output
Enter some data:123
value you enter is: 123
data type of 123 is: <class 'str'>
When we enter 123, it should be numeric data, but python treat every data which we take from user input as String data.
How to convert String to numeric data?
We have to explicitly convert the data into number if we want to process input data as a numeric data. For that we can use int function to convert String to Numeric data.
data=input("Enter some data:") print("data type of ",data, “before conversion is:”, type(data)) data=int(data) print("value you enter is:”, data) print("data type of ",data, “after conversion is:”, type(data))
Output
Enter some data:123
data type of 123 before conversion is: <class 'str'>
value you enter is: 123
data type of 123 after conversion is: <class 'int'>
As we see above that using int function we can convert input data into numeric data.
Similarly, we can convert the data into decimal, tuple, list etc.
data=input("Enter some data:") print("value you enter is:”, data) print("data type of ",data, “before conversion is:”, type(data)) f=float(data) t=tuple(data) l=list(data) print("float value is:",f) print("data type of ",data,"after conversion is:",type(f)) print("tuple value is:",t) print("data type of ",data,"after conversion is:",type(t)) print("list value is:",l) print("data type of ",data, “after conversion is:”, type(l))
Output
Enter some data:123
value you enter is: 123
data type of 123 before conversion is: <class 'str'>
float value is: 123.0
data type of 123 after conversion is: <class 'float'>
tuple value is: ('1', '2', '3')
data type of 123 after conversion is: <class 'tuple'>
list value is: ['1', '2', '3']
data type of 123 after conversion is: <class 'list'>