User Input

suggest change

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):

@Ver ≥ 2.3

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 to eval(input()) in Python3), which might easily become a vulnerability. See this article for further information on the risks of using this function.

@Ver end

@Ver ≥ 3.0

name = input("What is your name? ")
# Out: What is your name? _

@Ver end

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Getting Started:
* User Input

Table Of Contents
0 Getting Started
2 Filter
3 List
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve