Interactive input
To get input from the user, use the input
function (note: in Python 2.x, the function is called raw_input
instead, although Python 2.x has its own version of input
that is completely different):
name = raw_input("What is your name? ")
# Out: What is your name? _
Security Remark Do not use
input()
in Python2 - the entered text will be evaluated as if it were a Python expression (equivalent toeval(input())
in Python3), which might easily become a vulnerability. See this article for further information on the risks of using this function.
name = input("What is your name? ")
# Out: What is your name? _
The remainder of this example will be using Python 3 syntax.
The function takes a string argument, which displays it as a prompt and returns a string. The above code provides a prompt, waiting for the user to input.
name = input("What is your name? ")
# Out: What is your name?
If the user types "Bob" and hits enter, the variable name
will be assigned to the string "Bob"
:
name = input("What is your name? ")
# Out: What is your name? Bob
print(name)
# Out: Bob
Note that the input
is always of type str
, which is important if you want the user to enter numbers. Therefore, you need to convert the str
before trying to use it as a number:
x = input("Write a number:")
# Out: Write a number: 10
x / 2
# Out: TypeError: unsupported operand type(s) for /: 'str' and 'int'
float(x) / 2
# Out: 5.0
NB: It's recommended to use try
/except
blocks to catch exceptions when dealing with user inputs. For instance, if your code wants to cast a raw_input
into an int
, and what the user writes is uncastable, it raises a ValueError
.