Python input(): Read, Validate, Convert, and Secure User Input

Quick answer: Python input() reads one line from standard input and returns text. Treat that text as untrusted at the boundary: strip only what the input contract allows, validate it, convert it explicitly, and handle EOFError when stdin is closed. Never use eval() to turn a user string into Python code, and use getpass for passwords.

Python Pool infographic showing input text validation conversion EOFError getpass and safe user input flow
input() returns text; validate and convert at the boundary, handle EOF, avoid eval, and use getpass when the value is a password.

Python reads keyboard input with the built-in input() function. It shows an optional prompt, waits for the user to type a line, removes the trailing newline, and returns the result as a string.

name = input("What is your name? ")
print(f"Hello, {name}!")

The most important detail is that input() always returns text. If the user types 42, Python receives "42", not the integer 42. Convert and validate the value before using it as a number, date, option, or file path. For command-line flags rather than interactive prompts, Parse Boolean Values with Python argparse parses true and false values without the common bool(‘false’) mistake.

Quick answer

  • Use input("Prompt: ") to read one line from the keyboard.
  • Use int(), float(), or another parser when you need a non-string value.
  • Use try/except to handle invalid input.
  • Use getpass.getpass() for passwords or secrets.
  • Do not use eval(input()) on user input.

Basic input() syntax

input(prompt)

The prompt argument is optional. If you pass it, Python writes the prompt before reading the user’s line.

city = input("City: ")
print(f"You entered {city}")

Use clear prompts that include the expected format when needed:

date_text = input("Start date (YYYY-MM-DD): ")

Convert input to an integer

Because input() returns a string, wrap it with int() when you need an integer.

age_text = input("Age: ")
age = int(age_text)

print(age + 1)

If the user types something that is not a valid integer, int() raises ValueError. Real programs should catch that and ask again.

while True:
    age_text = input("Age: ")

    try:
        age = int(age_text)
        break
    except ValueError:
        print("Enter a whole number, such as 25.")

print(f"Next year you will be {age + 1}.")

Convert input to a float

Use float() when decimals are allowed.

price = float(input("Price: "))
quantity = int(input("Quantity: "))

total = price * quantity
print(f"Total: {total:.2f}")

Validate a yes/no answer

Normalize text input before comparing it. The common pattern is to remove surrounding whitespace and convert to lowercase.

answer = input("Continue? (y/n): ").strip().lower()

if answer in {"y", "yes"}:
    print("Continuing")
elif answer in {"n", "no"}:
    print("Stopping")
else:
    print("Please enter y or n.")

For compact conditional assignments after validation, see Python inline if.

Read multiple values from one line

Use split() to break one input line into separate strings.

first_name, last_name = input("Full name: ").split(maxsplit=1)
print(first_name)
print(last_name)

When every value should be converted to the same type, combine split() with a comprehension:

scores = [int(value) for value in input("Scores: ").split()]
print(scores)

You may also see map() used for this pattern:

x, y = map(int, input("x y: ").split())

Read Python map function if you want more examples of applying a conversion function to many values.

Handle EOFError

input() raises EOFError when it reaches end-of-file before reading a line. This can happen when input is piped, redirected, or closed.

try:
    command = input("Command: ")
except EOFError:
    command = "quit"

print(command)

This is useful for command-line programs that may run interactively or receive redirected input.

Read passwords safely

Do not use input() for passwords because it echoes what the user types. Use getpass.getpass() instead.

from getpass import getpass

password = getpass("Password: ")

Never log or print passwords, API keys, or tokens after reading them.

Do not use eval(input())

eval() executes Python expressions. Combining it with user input can run arbitrary code, so it is unsafe for normal input handling.

# Do not do this
value = eval(input("Value: "))

Parse the specific format you expect instead. Use int() for integers, float() for decimal numbers, json.loads() for JSON, or a dedicated parser for dates and other structured values.

Python 2 raw_input() note

In Python 2, raw_input() read a string and input() evaluated the entered text. Python 3 removed raw_input() and made input() return a string. If old code raises NameError: name 'raw_input' is not defined, replace raw_input(...) with input(...).

Common mistakes

  • Adding input directly to a number. Convert the input first: int(input("Count: ")).
  • Trusting input without validation. Users can press Enter, type extra spaces, or enter unexpected text.
  • Using split() without checking length. If the user enters too few or too many values, unpacking raises ValueError.
  • Reading secrets with input(). Use getpass() so the secret is not echoed.

Official references

The Python documentation explains input(), EOFError, getpass, and the standard stream used by sys.stdin.

Conclusion

Use input() for simple Python user input, then convert and validate the returned string before using it. That pattern keeps command-line programs predictable, avoids Python 2 confusion, and prevents unsafe shortcuts such as eval(input()).

Validate And Convert At The Boundary

Keep the original text long enough to report a useful error, then convert only after the accepted format is clear. A loop makes the retry behavior explicit and prevents invalid values from reaching business logic.

def read_positive_int(prompt):
    while True:
        raw = input(prompt).strip()
        try:
            value = int(raw)
        except ValueError:
            print("Enter a whole number.")
            continue
        if value <= 0:
            print("Enter a number greater than zero.")
            continue
        return value

# age = read_positive_int("Age: " )

Handle EOFError And KeyboardInterrupt

Interactive input can end without a line when a pipe closes, a test supplies an empty stream, or a user interrupts the program. Decide whether the command should return a default, show a short message, or exit with a nonzero status.

def read_optional_name():
    try:
        return input("Name (optional): " ).strip()
    except EOFError:
        return ""
    except KeyboardInterrupt:
        print("\nCancelled.")
        return ""

# name = read_optional_name()

Use getpass For Secrets

input() echoes what the user types in a normal terminal, so it is the wrong default for passwords and tokens. getpass.getpass() hides terminal echo where the environment supports it; do not print or log the returned secret.

from getpass import getpass

username = input("Username: " ).strip()
password = getpass("Password: " )

print("Signed in as", username)
# Send password only to the authenticated client, never to logs.

Parse Structured Values Safely

For several values, define a small grammar instead of evaluating arbitrary Python. Splitting a comma-separated list and validating each item is predictable, auditable, and easy to explain to a user.

def read_tags():
    raw = input("Tags, separated by commas: " )
    tags = [part.strip() for part in raw.split(",")]
    tags = [tag for tag in tags if tag]
    if not tags:
        raise ValueError("at least one tag is required")
    return tags

# print(read_tags())

The official input() documentation describes the prompt, line reading, and string return value. Python documents EOFError for end-of-file input and getpass for hidden terminal entry. Related Python Pool references include getpass and single-key input.

For safer input boundaries, compare getpass(), single-key input, and hashing sensitive values before deciding how a command should collect and protect data.

Frequently Asked Questions

What type does Python input() return?

input() returns a string after reading a line, even when the user types digits; convert and validate the text before numeric use.

How do I read an integer with input()?

Read the text, strip harmless surrounding whitespace, validate the accepted format, and pass it to int() with a clear error path.

How do I hide a password in Python?

Use getpass.getpass() instead of input() so the password is not echoed in a normal terminal.

Why does input() raise EOFError?

EOFError occurs when input reaches end-of-file without receiving a complete line, such as when stdin is closed or a script receives no interactive input.

Subscribe
Notify of
guest
2 Comments
Oldest
Newest Most Voted
A G Likitha
A G Likitha
4 years ago

Hi, I have gone through ur contents,
they are well explained…

But I have one doubt.i.e

In some python ide’s if I use input () ,
It shows EOF error
Could u please tell me the other forms of taking input from the Console(test cases)