Python, Accepting Input
By Flavio Copes
Learn how to accept user input in a Python command line app with the input() function, which pauses execution until the user types and presses enter.
To accept input from the user in a Python command line application, use the built-in input() function. It pauses the program, waits for the user to type something, and returns it when they press the enter key.
You already know how to display information to the user, using the print() function:
name = "Roger"
print(name)
Accepting input is the other half of the conversation:
print('What is your age?')
age = input()
print('Your age is ' + age)
This approach gets input at runtime, meaning the program will stop execution and will wait until the user types something and presses the enter key.
Adding a prompt
You don’t need a separate print() call for the question. input() accepts a prompt string as its argument:
age = input('What is your age? ')
print('Your age is ' + age)
The prompt shows up right before the cursor, on the same line. Note the space at the end: without it, the user types glued to the question mark.
input() always returns a string
Even if the user types a number, you get a string back. Type 42 and age holds '42'.
The concatenation above works because both values are strings. But try doing math and Python complains:
age = input('What is your age? ')
print(age + 1)
# TypeError: can only concatenate str (not "int") to str
Convert the value with int():
age = int(input('What is your age? '))
print(age + 1)
For decimal numbers, use float() instead.
What if the user types something invalid?
int() raises a ValueError when the value isn’t a number. Type twenty and the program crashes with:
ValueError: invalid literal for int() with base 10: 'twenty'
Handle it with a try block:
try:
age = int(input('What is your age? '))
except ValueError:
print('Please enter a number')
This way a typo shows a friendly message instead of a traceback.
Other ways to get input
input() covers interactive programs. You can also accept input at program invocation time, passing arguments on the command line. Python exposes them through sys.argv, and the argparse module helps you build more complex interfaces on top of that.
This works for command line applications. Other kinds of applications will need a different way of accepting input.
Related posts about python: