How to Get User Input in Python [With Examples]

Get User Input in Python

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.

SHARE:
nv-author-image

Brad Morton

I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Reply

Your email address will not be published. Required fields are marked *