Take Input from User in Python: input()
In Python, the input()
function is used to take user inputs.
Note that the behavior of input()
differs between Python 2 and Python 3. All the sample code below is for Python 3.
For more details on command line arguments and file input and output, see the following articles.
- Command line arguments in Python (sys.argv, argparse)
- Read, write, and create files in Python (with and open())
Basic usage of input()
You can use the input()
function to take user input and assign it to a variable.
val = input()
When this line is executed, it waits for input. You can input in the terminal or command prompt (cmd.exe
). For example, entering abc
will return the string 'abc'
.
val = input()
# abc
print(val)
# abc
print(type(val))
# <class 'str'>
To indicate that the program is awaiting user input, you can specify a prompt message in input()
.
val = input('Enter your name: ')
# Enter your name: Alice
print(val)
# Alice
print(type(val))
# <class 'str'>
In the sample code above, the output of print()
is shown in the comments for convenience. The following shows the result when the script file is actually executed in a terminal.
The contents of the script file:
val = input('Enter your name: ')
print('You are', val)
It waits for input at Enter your name:
, and in this example, Alice
is entered.
$ python3 input_usage_script.py
Enter your name: Alice
You are Alice
Take input as numerical values: int()
, float()
The input()
function accepts keyboard input as a string (str
).
val = input('Enter an integer: ')
# Enter an integer: 100
print(val)
# 100
print(type(val))
# <class 'str'>
To convert a string (str
) to an integer (int
) or a floating-point number (float
), use int()
, float()
.
i = int(input('Enter an integer: '))
# Enter an integer: 100
print(i)
# 100
print(type(i))
# <class 'int'>
If a string can't be converted to a number, an error will occur.
# i = int(input('Enter an integer: '))
# Enter an integer: abc
# ValueError: invalid literal for int() with base 10: 'abc'
Since user input can be unpredictable, it is important to handle exceptions.
For example, if you want to treat input that can't be converted as a specific default value, do as follows.
try:
i = int(input('Enter an integer: '))
except ValueError:
i = 0
# Enter an integer: abc
print(i)
# 0
You can also use an infinite loop with a while
statement to repeat input()
until a valid value is entered.
while True:
try:
i = int(input('Enter an integer: '))
break
except ValueError:
print('Invalid input!')
# Enter an integer: abc
# Invalid input!
# Enter an integer: 100
print(i)
# 100
Take multiple inputs as a list
Fixed number of inputs
To take a fixed number of inputs, you can simply call input()
multiple times.
l = []
l.append(input('Enter the first value: '))
l.append(input('Enter the second value: '))
l.append(input('Enter the third value: '))
# Enter the first value: x
# Enter the second value: y
# Enter the third value: z
print(l)
# ['x', 'y', 'z']
Variable number of inputs: while
, iter()
, split()
To handle a variable number of inputs, you can use a while
loop, iter()
, or split()
.
For how to convert a list of strings to a list of numbers, refer to the following article.
while
An infinite loop with a while
statement can be used to repeat input()
until over
is entered.
l = []
print('Enter "over" then finish')
while True:
val = input('Enter a value: ')
if val == 'over':
print('FINISH')
break
l.append(val)
# Enter "over" then finish
# Enter a value: x
# Enter a value: y
# Enter a value: z
# Enter a value: over
# FINISH
print(l)
# ['x', 'y', 'z']
iter()
Using the built-in function iter()
makes the code simpler. As in the above example using the while
loop, the following example repeats input()
until over
is entered.
l = list(iter(input, 'over'))
# x
# y
# z
# over
print(l)
# ['x', 'y', 'z']
The iter()
function generates an iterator that continues to return values until the callable object, specified as the first argument (in this case input
), returns the second argument (in this case 'over'
).
If you want to specify an argument to input()
, use a lambda expression. The lambda expression itself has no arguments.
l = list(iter(lambda: input('Enter a value: '), 'over'))
# Enter a value: x
# Enter a value: y
# Enter a value: z
# Enter a value: over
print(l)
# ['x', 'y', 'z']
split()
You can also ask the user to enter inputs separated by some delimiter, and divide it into a list using the split()
method.
val = input('Enter values separated by commas: ')
# Enter values separated by commas: x,y,z
print(val)
# x,y,z
l = val.split(',')
print(l)
# ['x', 'y', 'z']
The above example uses a comma as the delimiter, but you can also use a space or any other character.
Take multiline input
Since input through input()
is confirmed by pressing the Enter key, it is impossible to input a value with a line break.
As demonstrated above, you can first use a while
loop or iter()
to take the input as a list. After that, you can utilize the join()
method to convert it into a string, placing line breaks between each element.
When using iter()
, you can pass it directly as an argument to join()
without needing to convert it to a list first. In the following example, the second argument to iter()
is an empty string ''
, so input ends when the Enter key is pressed twice.
s = '\n'.join(iter(input, ''))
# Line1
# Line2
# Line3
#
print(s)
# Line1
# Line2
# Line3
print(type(s))
# <class 'str'>
Differences between Python 2 and Python 3: raw_input()
vs. input()
In Python 2, both raw_input()
and input()
functions are available. Python 2's raw_input()
is equivalent to Python 3's input()
.
raw_input()
in Python 2 and input()
in Python 3
Python 2's raw_input()
and Python 3's input()
are functions that obtain input from the keyboard as a string (str
).
- 2. Built-in Functions - raw_input() — Python 2.7.18 documentation
- Built-in Functions - input() — Python 3.11.4 documentation
input()
in Python 2
In Python 2, the input()
function evaluates the input string as an expression using eval()
. It is equivalent to eval(raw_input())
.
For example, when 1 + 2
is input into Python 2's input()
, it is treated as an expression and evaluated to 3
, rather than simply treated as the string '1 + 2'
.
There is no function in Python 3 that evaluates expressions in the same way as input()
in Python 2.
When errors occur
If an error occurs with input()
, it's possible that there's confusion between Python 2 and Python 3. In such cases, it's recommended to check the Python version using sys.version
where the error occurs.