Sitelet https://howtodoinjava.com/python-builtin/python-input/

Python input() Function: Read and Validate User Input

Read user input in Python with input(), convert it to numbers safely with a retry loop, read several values from one line, and handle EOFError cleanly.

Python

The Python input() function shows an optional prompt, waits for the user to type a line, and returns that line as a string without the trailing newline. Small console scripts use it whenever they need a value from the person at the keyboard.

name = input("Your name: ")    # the user types Lokesh
print("Hello,", name)          # Hello, Lokesh

The catch is that input() always returns a str. In the rest of the article, we convert input to numbers safely, read several values from one line, clean up yes-or-no answers, and handle the end of input. The sample sessions show what the terminal displays when we type the answers, on Python 3.14.

1. Syntax and Return Value

The signature is input(prompt), where prompt is optional and printed without a newline after it. So we end the prompt with a space or a colon and a space.

input([prompt]) -> str

The function either returns the typed line as a str, with the trailing newline removed, or raises EOFError when the input ends before a line arrives. The result is a string even when the user types a number, which is why the next section converts it.

answer = input()                    # no prompt
answer = input("How many pizzas? ") # prompt on the same line as the typing

2. Reading Numbers Safely

Calling int() on the result raises ValueError when the user types something that is not a whole number, so we wrap the conversion in a retry loop. A bare int(input()) crashes on the first typo.

while True:
    text = input("How many pizzas? ")
    try:
        count = int(text)
        break
    except ValueError:
        print(f"'{text}' is not a whole number, try again")
print("Ordering", count, "pizzas")
How many pizzas? three
'three' is not a whole number, try again
How many pizzas? 2.5
'2.5' is not a whole number, try again
How many pizzas? 3
Ordering 3 pizzas

The int() function accepts surrounding spaces, so int(” 42 “) returns 42, but it rejects an empty string and decimals. For decimals we use float() in the same loop.

3. Several Values on One Line

When the user types values separated by spaces, split() breaks the line into strings and map() converts each one.

w, h = map(int, input("Width and height: ").split())   # user types: 4 5
area = w * h                                           # 20

Typing three numbers instead of two raises ValueError: too many values to unpack (expected 2), so in real tools this line also goes inside a try block.

4. Cleaning Up Text Answers

Users add spaces and mix upper and lower case. Calling strip() and lower() before the comparison accepts ” Yes “, “y” and “YES” alike.

answer = input("Extra cheese? ").strip().lower()   # user types: " Yes "
cheese = answer in ("y", "yes")                   # True

5. EOFError and Other Pitfalls

When there is no more input, for example when a script reads from an empty pipe or the user presses Ctrl+D (Ctrl+Z and Enter on Windows), input() raises EOFError. Scripts that may run without a keyboard catch it.

try:
    city = input("City: ")
except EOFError:
    city = "unknown"
  • Never pass the result to eval(); it runs whatever the user types as Python code.
  • For passwords, use getpass.getpass(), which hides the typed characters.
  • Python 2 code uses raw_input(); in Python 3 the same function is called input().

6. Building a Console Menu with input()

A console menu reads a choice and repeats until the user quits. A while True loop with a break on q handles it, and unknown choices get a message instead of a crash.

cart = []
while True:
    choice = input("[a]dd, [l]ist, [q]uit: ").strip().lower()
    if choice == "q":
        break
    elif choice == "a":
        cart.append(input("Item: ").strip())
    elif choice == "l":
        print("Cart:", ", ".join(cart) or "empty")
    else:
        print("Unknown choice:", choice)
[a]dd, [l]ist, [q]uit: a
Item: tea
[a]dd, [l]ist, [q]uit: x
Unknown choice: x
[a]dd, [l]ist, [q]uit: l
Cart: tea
[a]dd, [l]ist, [q]uit: q

7. Reading Multiple Lines, Pipes and Timeouts

Scripts that read more than one value soon outgrow a single prompt.

7.1. How do we read several lines until the user enters a blank line?

We loop until an empty line, and we also stop when the input ends.

lines = []
while True:
    try:
        line = input()
    except EOFError:
        break
    if line == "":
        break
    lines.append(line)

7.2. How do we read input that is piped into the script?

For whole files or pipes, sys.stdin is simpler than calling input() in a loop, for example for line in sys.stdin:. The input() function also reads piped data, one line per call.

7.3. Can input() time out?

No, input() waits until a line arrives. A timeout needs another approach, such as select.select() on sys.stdin on Linux and macOS, or reading in a separate thread, which also works on Windows.

8. Conclusion

Reading one line is all input() does, and everything else is our job. We convert numbers inside a try block with a retry loop, normalize text with strip() and lower(), and catch EOFError when the script might run without a user.

9. References

Happy Learning !!

Source Code on Github

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.