Python / input() / Read User Input into a Variable

Python's input() reads one line from standard input and returns a string. Assign it with name = input() to use that text through a variable; numeric input still needs conversion with int() or float() before arithmetic. The trailing newline is removed, but other leading and trailing whitespace is preserved.

Read one line into a variable

These examples need Python 3 and no extra packages. Their outputs were checked with supplied standard input on Python 3.12.14. Save each complete example as UTF-8 in input_demo.py and run python input_demo.py in a terminal; your interpreter may be named python3. Replace the file contents for each independent example.

Run this code, type JB and press Enter. There is no prompt in the example, so initially waiting without displaying anything is normal.

name = input()
print(f"Hello, {name}!")
print(type(name).__name__)

The program prints the following. All result blocks show program output only, excluding the terminal's echo of the characters you type.

Hello, JB!
str

The optional prompt described in the input() documentation lets you display instructions with input("Name: "). The prompt is not part of the returned value. Standard input can also come from a file or another program; input() is not limited to keyboard entry.

Convert numeric text before calculating

Enter 0012 on the first line, then 1.25 on the second. Two input() calls read two separate lines; do not put both values on one line.

text = input()
print(repr(text))
print(text + "1")
number = int(text)
print(number + 1)
price = float(input())
print(price * 2)
'0012'
00121
13
2.5

repr() makes the string representation visible, including quotes. Adding "1" to the text joins it into 00121; converting to an integer before adding 1 gives 13. Conversion discards leading zeros, so keep postal codes and product identifiers as text when their formatting matters.

int("1.25") and int("hello") raise ValueError. Use float when a floating-point value suits the task; this example uses a decimal point. Currency symbols and grouping commas are not cleaned automatically. Binary floating-point also requires separate consideration when exact decimal money arithmetic is needed.

Retry invalid input with complete validation

Successful conversion and an acceptable value are different conditions. This example accepts a nonnegative age. Enter hello, -1 and 20, each on its own line:

while True:
    try:
        text = input()
    except EOFError:
        print("Input ended.")
        break
    try:
        age = int(text)
    except ValueError:
        print("Enter a whole number.")
        continue
    if age < 0:
        print("Enter 0 or greater.")
        continue
    print(f"Accepted: {age}")
    break
Enter a whole number.
Enter 0 or greater.
Accepted: 20

ValueError handles text that cannot become an integer; the separate negative-value condition rejects a successfully converted negative number. A blank line also fails integer conversion. A valid value ends the loop with break. Following the exception-handling guidance, catch specific expected errors. EOF ends this loop rather than asking for input forever.

Preserve or remove whitespace deliberately

For the first line, type two spaces, JB, then two spaces. For the second line, press Enter without typing characters.

text = input()
print(repr(text))
print(repr(text.strip()))
empty = input()
print(repr(empty))
print(empty == "")
'  JB  '
'JB'
''
True

input() removes the newline, leaving the spaces around JB. str.strip() returns a new string without surrounding whitespace; it does not change the original. Do not apply it indiscriminately when spaces are meaningful. A blank line is "", not None. Decide whether a whitespace-only line should count as empty before testing a stripped value.

Read two values from one line

To accept two integers from one input() call, split the text and convert each part. Enter 10 20 on one line:

parts = input().split()
if len(parts) != 2:
    print("Enter exactly two integers.")
else:
    try:
        left, right = map(int, parts)
    except ValueError:
        print("Use whole numbers.")
    else:
        print(left + right)
30

split() without a separator treats consecutive whitespace as one separation. Check for exactly two parts before map passes each to int. Entering only 10 or three values produces the count message; 10 hello produces the integer message. This small example ends after invalid input; use a loop like the earlier example if retries are required.

Distinguish EOF from a blank line

EOF means End of File: the input stream has ended. If input() cannot read any more data, it raises EOFError instead of returning a blank line. This code attempts two reads. Supplying a stream containing just one newline gives:

for index in range(2):
    try:
        text = input()
    except EOFError:
        print("EOF")
        break
    print(repr(text))
''
EOF

The first read obtains an empty string; the second encounters EOF. To try this interactively, press Enter for the first read, then send end-of-input for the second. Windows consoles commonly use Ctrl+Z followed by Enter; macOS and Linux terminals commonly use Ctrl+D on an empty input line. The terminal or IDE can handle these keys differently.

If an IDE output pane does not accept input, run the script in a terminal or input-capable console. With online judges or redirected files, check that the required number of lines is supplied. Waiting for input and reaching EOF are different states. Converting a user's text to a number does not require executing it with eval().