Python Reference ยท Built-in Functions
Python input() function
Reference for Python input(): read a line from the user as a string, show a prompt, convert to numbers, handle EOFError and invalid input safely.
The input() function reads one line from standard input, usually the keyboard, and returns it as a string. The trailing newline is removed. If you pass a prompt, it is written to standard output first, without a newline.
Whatever the user types arrives as text. To work with numbers you must convert the string yourself with int() or float(), and a robust program handles the case where the conversion fails.
name = input("Your name: ") print("Hello,", name)
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
input() input(prompt)
| Name | Description |
|---|---|
prompt |
Optional. Text written to standard output (without a newline) before reading. Non-strings are converted with str(). |
Return value: the line as a str, without the trailing newline.
Raises: EOFError when the input ends before any characters are read (Ctrl+D on Unix, Ctrl+Z then Enter on Windows, or an empty stdin in a script).
Usage notes
- Always a string.
input("n: ") + 1raisesTypeError. Convert first:int(input(...)). - Validate conversions.
int("abc")raisesValueError. Wrap the conversion intry/exceptand ask again, as in the second example. - Whitespace is kept. Only the newline is stripped, so use
.strip()to remove stray spaces. - Blocks until a line arrives. In a script, reading from a pipe or file works the same way: each call consumes one line.
- End of input. Loops that read until the user is finished should catch
EOFError, or usefor line in sys.stdin:to read all lines. - No hidden input.
input()echoes characters. For passwords usegetpass.getpass()from the standard library. - Python 2 difference. Python 2's
input()evaluated the text as code; Python 3'sinput()is the oldraw_input(). - Browser runner. In the examples on this site, the Input box above the editor supplies the lines, one per
input()call.