Juicy lil' bytes

How to Get User Input From the Command Line in a Python Script

Here is an example Python command line script that demonstrates how to obtain data from the user with the Python 2 or 3 interpreter.

The built-in function returns the string that was entered by the user. Pass the query prompt to the user as an argument to the built-in function like this:

Python 2

User Input in Python 2
1
response = raw_input("Please enter your name: ")

Python 3

User Input in Python 3
1
response = input("Please enter your name: ")

Testing for the Python Version

To add the Python interpreter version testing logic to your script, use the sys.version_info tuple:

User Input with Python Version Testing
1
2
3
4
5
6
7
8
from sys import version_info

py3 = version_info[0] > 2 #creates boolean value for test that Python major version > 2

if py3:
  response = input("Please enter your name: ")
else:
  response = raw_input("Please enter your name: ")