Getting User Input from Keyboard
There are two functions that can be used to read data or input from the user in python: raw_input() and input(). The results can be stored into a variable.
raw_input() – It reads the input or command and returns a string.
input() – Reads the input and returns a python type like list, tuple, int, etc.
name = raw_input (“what is your name? ”) # return type of raw input is always string age = input (“what is your age ”) # This can be different from string print “user entered name as: ” + name print “The type of the name is: ”, print type (name) print “user entered age as: ” + str (age) print “The type of age is: ”, print type (age)
Assigning Values after running it:
what is your name?
what is your age?
It will give the result as follows:
user entered name as: abc
The type of the name is: <type ‘str’>
user entered age as: 21
The type of the age is: <type ‘int’>
There was no type given above for the data when entered. Name has been taken as string type, while age has been taken as integer type Python. Basically, the difference between raw_input and input is that the return type of raw_input is always string, while the return type of input need not be string only. Python will judge as to what data type will it fit the best. In case you have entered a number, it will take it as an integer. But if it is raw_input it would certainly be string.
Note: Whenever you write a lot of code, it’s always advisable to write it in one of the IDEs as it is very helpful. In case you do not get proper indentation, it will directly show you errors. If you have any problem as well, it’s very easy to debug in PyCharm or any other IDE that you may want to use.
Got a question for us? Please mention them in the comments section and we will get back to you.