This article covers getting user input on the command line using Python 2 or 3 and includes some useful examples.
Get User Input in Python 3
Python 3 uses the input() function to collect user input:
myText = input("Enter some text:") print("You entered the text: " + myText)
Get User Input in Python 2
If you’re still using Python 2, you will use the raw_input() function instead:
myText = raw_input("Enter some text:") print "You entered the text: ", myText # Python 2 uses different syntax to print output
Typing Input
All input collected using the above functions will create a string variable. If you are collecting numerical information, you can change the type using the int() and float() functions:
myText = input("Enter some text, it will be converted to a number variable:") myInteger = int(myText) # Converts the input text to an integer myFloat = float(myText) # Converts the input text to a float number
The above example assumes you are using Python 3.
Handling Bad Input
In the above example, where the text is converted to a number, Python will throw an error if the user hasn’t entered a valid number.
This can be handled using a try/catch block:
try: myText = input("Enter some text, it will be converted to a number variable:") myInteger = int(myText) # Converts the input text to an integer myFloat = float(myText) # Converts the input text to a float number except ValueError: print("User has input in invalid number that could not be converted")
Handling bad user input is something you should always do – users are not predictable (or reliable), ever.