Learn How to Get Input in Python: Absolute Beginners Tutorial

Every interactive Python program needs a way to receive data from the person running it. The input() function is Python's built-in tool for that. It pauses your program, waits for the user to type something, and returns that text as a string you can work with.

Before writing any program that interacts with a real person, you need to understand two things: how input() works, and what it gives you back. Those two facts explain most of the beginner mistakes you will encounter with user input in Python.

What input() does

When Python reaches a line containing input(), execution stops completely. The cursor blinks. Python is waiting. The moment the user presses Enter, Python resumes — taking everything typed before that Enter and returning it as a single string value.

Here is the minimal form:

python
response = input()
print(response)

That is a complete, working program. Python will display a blank line and wait. Whatever the user types will be printed back. There is no prompt telling the user what to type, which is usually not ideal — but the mechanics are correct.

Note

input() reads from standard input (stdin). In a terminal, that is the keyboard. In some environments like IDLE or Jupyter Notebooks, a dialog box or inline field appears instead. The behavior of your program is the same regardless of the environment.

The function signature is straightforward:

python
input([prompt])

The square brackets indicate that the prompt argument is optional. You can call input() with nothing inside, or pass in a string to display to the user.

The return value is always a string

This is the single most important fact about input(). No matter what the user types — a number, a date, a single letter — Python hands it back as a str. There is no automatic detection of type. Beginners frequently run into TypeError or unexpected behavior because they forget this rule.

python
x = input("Enter a number: ")
print(type(x))   # <class 'str'>

Even if the user types 42, the value of x is the string '42', not the integer 42. You will see how to convert it in the type conversion section below.

code builder click a token to place it

Build a line that reads user input and stores it in a variable called name:

your code will appear here...
input() print(name) name == = str()
Why: name = input() uses the single assignment operator = (not the comparison ==), and calls input() with no prompt. Wrapping in str() is unnecessary because input() already returns a string.

The prompt parameter

Calling input() with no argument works, but it leaves the user staring at a blank cursor with no idea what the program expects. The prompt parameter fixes that. Pass any string and Python will display it immediately before waiting for input — on the same line, with no newline added.

python
name = input("Enter your name: ")
print("Hello,", name)

Notice the trailing space inside the string: "Enter your name: ". Without it, the user's cursor would appear directly after the colon, making the output look cramped. Adding a space before the closing quote is a simple formatting habit worth building from the start.

Pro Tip

For longer prompts that span multiple lines, use a triple-quoted string so you can break the prompt across lines naturally:

answer = input("""Choose an option:
  1 — Add item
  2 — Remove item
Your choice: """)

Python prints the entire string before pausing, so the user sees all three lines before typing.

Using prompt output in a sentence

A prompt can be as simple or as descriptive as the situation requires. Here are a few common patterns:

python
# Minimal
city = input("City: ")

# Full sentence
color = input("What is your favorite color? ")

# With a hint about expected format
dob = input("Date of birth (YYYY-MM-DD): ")

# Multi-value on one line using split()
first, last = input("First and last name: ").split()

The .split() call at the end of the last example separates the user's input at whitespace and unpacks the result into two variables. This is a common pattern for collecting two values with a single prompt. Keep in mind that if the user types more or fewer than two words, Python raises a ValueError — so this pattern works best when you control the expected format or validate the input afterward.

Choosing a prompt style

The table below compares the three main calling styles so you can choose the right one for each situation:

Prompt displayed
None — cursor appears on a blank line
When to use
Rarely. Only useful in scripts where context is obvious or a prompt is printed separately with print()
Prompt displayed
Inline — user types directly after the prompt text on the same line
When to use
The standard approach for any interactive program. Clear, concise, and requires no extra print statement.
Prompt displayed
On the line above the cursor — the cursor appears on its own new line
When to use
When the instructions are long enough to warrant their own line, or when you want to visually separate the prompt from the entry field.

Type conversion: why input() is always a string

The input() function has no way to know whether the user intends to type a number, a date, or free-form text. It captures raw keystrokes and returns them as a string. When your program needs a specific type, you perform the conversion yourself.

Warning

Forgetting to convert is a common cause of TypeError for beginners. If you write age = input("Age: ") and then try age + 1, Python raises TypeError: can only concatenate str (not "int") to str. The fix is always the same: wrap input() with the conversion function you need.

Converting to integer

python
age = int(input("Enter your age: "))
print("In ten years you will be", age + 10)

Converting to float

python
price = float(input("Enter price: "))
tax = price * 0.08
print(f"Total with tax: ${price + tax:.2f}")

Handling bad input with try/except

If the user types letters when your program calls int(input(...)), Python raises a ValueError and the program crashes. A try/except block lets you catch that error and respond gracefully:

python
try:
    score = int(input("Enter your score: "))
    print("Score recorded:", score)
except ValueError:
    print("That is not a valid number. Please try again.")

This pattern is the foundation of any real input-validation loop. You will build on it whenever you need to keep asking until the user provides acceptable data.

"Errors should never pass silently."

spot the bug click the line that contains the bug

The function below asks for a user's birth year and calculates their age. One line contains a bug that causes a TypeError. Click the line you think is wrong, then hit check.

1 current_year = 2026
2 birth_year = input("Enter your birth year: ")
3 age = current_year - birth_year
4 print("You are approximately", age, "years old.")
The fix: Change line 3 to age = current_year - int(birth_year), or better, convert on line 2: birth_year = int(input("Enter your birth year: ")). The bug is that input() returns a string, so subtracting it from the integer current_year causes a TypeError. Python cannot subtract a string from an integer without an explicit conversion.

Validation: stripping, looping, and range checks

Getting text from input() is only the first half of the job. In any program that matters, you also need to make sure the value is clean, the correct type, and within acceptable bounds. Three patterns cover the overwhelming majority of those requirements.

Stripping whitespace before converting

When a user types with an accidental leading space — or pastes text that carries surrounding whitespace — int(" 42 ") raises a ValueError, even though the number is clearly there. Calling .strip() on the raw string before conversion removes those spaces and prevents a needless crash.

python
# Without strip() — "  42  " raises ValueError
age = int(input("Enter your age: "))

# With strip() — safe regardless of extra whitespace
age = int(input("Enter your age: ").strip())

# For text values, strip() removes accidental spaces from names too
name = input("Enter your name: ").strip()

Make .strip() a reflex whenever you convert user input. It does not change valid input and it prevents unnecessary failures from whitespace that the user never intended to type.

Re-prompt loops: asking until valid

A single try/except catches one bad attempt, but it does not ask again. A while True loop paired with try/except is the standard pattern for keeping the program running until the user provides acceptable data.

python
while True:
    try:
        age = int(input("Enter your age: ").strip())
        break          # only reached when int() succeeds
    except ValueError:
        print("Please enter a whole number.")

print(f"You entered: {age}")

The loop runs indefinitely until a valid integer is entered, at which point break exits. The ValueError branch prints a message and lets the loop repeat — the user never sees a traceback.

Range and choice validation

Type conversion confirms that the user typed something numeric. It does not confirm that the number makes sense for your program. A second check inside the loop — after the conversion — handles that.

python
# Range check — keep asking until the number is in bounds
while True:
    try:
        score = int(input("Enter a score (0–100): ").strip())
        if not 0 <= score <= 100:
            print("Score must be between 0 and 100.")
            continue
        break
    except ValueError:
        print("Please enter a whole number.")

# Choice check — keep asking until a valid menu option is chosen
valid_choices = {"1", "2", "3"}
while True:
    choice = input("Choose 1, 2, or 3: ").strip()
    if choice in valid_choices:
        break
    print(f"'{choice}' is not a valid option. Try again.")

Accepting yes/no responses

Python's bool() function does not work with user input the way beginners expect. bool(input(...)) returns True for any non-empty string — including the word "no" — which is almost never what you want. The correct approach is to normalize the raw string and compare it yourself.

python
# Wrong — bool() on a string is almost never what you want
confirmed = bool(input("Continue? (yes/no): "))  # "no" evaluates to True!

# Correct — compare the normalized string
while True:
    raw = input("Continue? (yes/no): ").strip().lower()
    if raw in ("yes", "y"):
        confirmed = True
        break
    elif raw in ("no", "n"):
        confirmed = False
        break
    print("Please type yes or no.")
The full validation chain

For most interactive programs, the complete pattern is: call input(), call .strip(), convert the type inside try/except, check the value against your constraints, and break only when everything passes. That sequence handles the vast majority of bad input without external libraries.

Reusable input helpers: extracting the pattern into a function

Once you have written the same while True / try / except / range-check / break loop two or three times in the same script, it is time to extract it. A reusable helper function takes the prompt, the converter, and an optional validator as arguments, and keeps your calling code clean. This is the natural next step after the inline pattern.

python
def get_input(prompt, converter=str, validator=None, error_msg="Invalid input. Try again."):
    """
    Ask for input repeatedly until it passes conversion and validation.

    prompt     -- string displayed to the user
    converter  -- callable applied to the stripped string (e.g. int, float, str)
    validator  -- optional callable that receives the converted value; return True to accept
    error_msg  -- message printed when conversion or validation fails
    """
    while True:
        try:
            raw = input(prompt).strip()
            value = converter(raw)
            if validator is not None and not validator(value):
                print(error_msg)
                continue
            return value
        except (ValueError, EOFError):
            print(error_msg)

# Usage examples
age    = get_input("Enter your age: ",         int,   lambda v: 0 < v < 130,    "Age must be between 1 and 129.")
score  = get_input("Enter score (0-100): ",    int,   lambda v: 0 <= v <= 100,  "Score must be 0-100.")
price  = get_input("Enter price: ",            float, lambda v: v >= 0,         "Price cannot be negative.")
name   = get_input("Enter your name: ",        str,   lambda v: len(v) > 0,     "Name cannot be empty.")

The converter parameter defaults to str, so calling get_input("Enter your name: ") with no extras behaves exactly like the inline pattern. Passing int or float adds type conversion. Adding a validator lambda adds the range or format check without repeating the loop structure. The EOFError handler inside the helper makes every call safe in non-interactive environments.

Why a callable validator beats a hardcoded if-check

Passing a lambda or function as the validator means the helper does not need to know anything about your domain rules. You can swap validators at call sites — lambda v: v in {"admin", "user", "guest"} for a role field, lambda v: v.isdigit() and len(v) == 5 for a ZIP code — without changing the helper itself. The pattern scales to any input type without duplicating the loop.

Collecting multiple values on one line with map()

The prompt-style comparison table showed first, last = input("First and last name: ").split() for two strings. The same technique extends to numeric values using map(), which applies a function to each element produced by .split() before unpacking. This avoids two separate input() calls when your program needs several values that naturally belong on the same line.

python
# Two integers on one line
x, y = map(int, input("Enter x and y (space-separated): ").split())

# Three floats -- e.g., RGB values
r, g, b = map(float, input("Enter R G B values: ").split())

# An unknown number of integers on one line -- store them in a list
numbers = list(map(int, input("Enter integers separated by spaces: ").split()))
print("Sum:", sum(numbers))
print("Max:", max(numbers))

The map(int, ...) call is lazy — it produces values one at a time as the unpacking consumes them. Wrapping it in list() is only necessary when you need to store all values for later use rather than unpack them immediately. This pattern raises ValueError if any token cannot be converted, and raises ValueError if the token count does not match the number of variables you are unpacking — both errors you should catch in a try/except when the input format is not guaranteed.

Under the hood: CPython, readline, and auditing

Understanding what input() does at the implementation level explains several behaviors that beginners find puzzling — including why it sometimes behaves differently in IDLE versus a terminal, and why security-conscious Python code wraps it with audit hooks.

What CPython actually does when input() runs

In CPython — the reference implementation you download from python.org — input() is implemented in C inside Python/bltinmodule.c. When your script reaches a call to input(), CPython performs these steps in sequence:

What happens
Before reading anything, CPython raises a builtins.input auditing event with the prompt string as the argument. Any registered audit hooks receive this event.
Why it matters
Security tools and runtime monitoring frameworks can intercept every input() call. This is how some sandboxed environments block interactive input entirely — they register a hook that raises an exception on this event.
What happens
If you passed a prompt string, CPython writes it to sys.stdout without appending a newline. This is why the user's cursor appears on the same line as the prompt text.
Why it matters
If you have redirected sys.stdout to a file or custom stream, the prompt goes there too — it does not bypass your redirection. Flushing stdout before the call is occasionally necessary in buffered contexts.
What happens
CPython reads characters from sys.stdin until it sees a newline (Enter key). The trailing newline is stripped before the string is returned. This is why len(input()) correctly reflects what the user typed, not what was sent over the wire.
Why it matters
When stdin is piped from a file rather than a keyboard, the same stripping behavior applies. Each line you redirect in becomes one call to input(). When the file is exhausted, the next call raises EOFError.
What happens
After reading successfully, CPython raises a second auditing event — builtins.input/result — with the returned string as its argument.
Why it matters
This second event lets audit hooks inspect what the user actually typed, not just what was asked. Enterprise security tools use both events to log input for compliance or anomaly detection without modifying application code.

The readline integration you may not know about

When Python detects that the readline module is loaded, input() automatically delegates to it instead of reading from stdin directly. This enables features most beginners never notice — but that explain certain terminal behaviors.

With readline active, pressing the Up arrow in a Python script's prompt replays previous entries from a history buffer. Tab completion becomes available if a completer function is registered. These capabilities exist because readline intercepts the low-level input call and adds GNU Readline (or editline on macOS) line-editing on top of it.

Platform note

The readline module is available on Unix-like systems (Linux, macOS). It is not available on Android, iOS, or WebAssembly (WASI). On Windows, input() uses the platform's built-in console API. If you are building a cross-platform CLI tool and need history or completion, check for readline availability at runtime before relying on it.

python
# Enable readline history so the user can press Up to recall previous entries
try:
    import readline
    readline.set_history_length(50)
except ImportError:
    pass  # readline not available on this platform — input() still works normally

name = input("Enter your name: ")

EOFError: when input() finds nothing to read

One error beginners encounter outside the normal interactive flow is EOFError. It occurs when input() reaches the end of its input stream before the user (or piped data) provides a complete line. Common triggers include pressing Ctrl+D on Linux and macOS or Ctrl+Z then Enter on Windows, as well as running a script in an automated environment where no stdin is attached.

python
# Robust input loop that handles both bad values and EOF
while True:
    try:
        raw = input("Enter a positive integer: ")
        value = int(raw)
        if value <= 0:
            print("Must be greater than zero. Try again.")
            continue
        break
    except ValueError:
        print("Not a valid integer. Try again.")
    except EOFError:
        print("\nNo input available. Exiting.")
        raise SystemExit(1)

The EOFError branch is easy to overlook when testing interactively, because you never hit that key by accident. It becomes essential when your program might run in a pipeline, a CI/CD job, a container with no attached terminal, or any non-interactive context.

Reading from stdin directly

input() is convenient, but it reads exactly one line at a time and blocks until the user presses Enter. There are situations where reading from sys.stdin directly gives you more control.

python
import sys

# Read all lines piped into the script — e.g., echo "hello" | python script.py
for line in sys.stdin:
    stripped = line.rstrip('\n')
    print("Got:", stripped)

# Read everything at once into a single string
# data = sys.stdin.read()

The key difference from input(): iterating over sys.stdin does not strip the newline automatically, and it returns an empty string at EOF rather than raising EOFError. That is often more convenient when processing piped data in a loop. sys.stdin.read() reads everything at once and blocks until EOF — useful for multi-line input where you do not know how many lines to expect.

When to use sys.stdin vs input()

Use input() when your program is interactive — you want a prompt, one response, and a newline stripped. Use sys.stdin when processing piped data, batch files, or multi-line blocks where the number of lines is unknown in advance. The two approaches can coexist in the same program: input() for interactive prompts, sys.stdin for automated pipelines.

Secure input: when not to use input()

The Python documentation describes input() as a function that reads from standard input. That description includes an important implication: whatever the user types is echoed to the terminal in plain text. For passwords, API keys, and other secrets, that echo behavior is a security problem.

"Read a string from standard input."

The standard library provides a direct solution: the getpass module. Its getpass.getpass() function works similarly to input() — it displays a prompt and waits for the user to type — but it disables terminal echo so the typed characters are never displayed on screen.

python
import getpass

# Prompt is displayed; typed characters are NOT echoed to the terminal
password = getpass.getpass("Enter password: ")

# getpass() returns a str — the same type as input()
# Conversion and validation work the same way
if len(password) < 8:
    print("Password must be at least 8 characters.")

getpass.getpass() raises GetPassWarning — a subclass of UserWarning — when it cannot suppress echo, for example when running in certain IDE terminals or notebooks. That warning tells you the secret will be visible. In production CLI tools that handle credentials, always use getpass and never input() for anything sensitive.

Echo
Characters are displayed as the user types
Use for
Names, numbers, choices, any non-sensitive input
Return type
str — always
Echo
Characters are suppressed — nothing appears on screen
Use for
Passwords, API keys, tokens, PINs, any sensitive credential
Return type
str — same as input(); convert and validate the same way
Warning
Emits GetPassWarning if echo cannot be suppressed in the current environment

How to get user input in Python

Follow these four steps every time you need to collect input from a user. The pattern is the same whether you are writing a simple greeting script or a full command-line application.

  1. Call input() and store the result

    Write a variable name, the assignment operator =, and then input(). Python will pause and wait for the user to press Enter. The typed text is stored as a string in your variable: response = input().

  2. Add a prompt to guide the user

    Pass a descriptive string as the argument to input(). It appears on the same line where the user types. Always include a trailing space so the cursor does not sit flush against your text: response = input("Enter your name: ").

  3. Convert the input to the type you need

    Wrap input() with int(), float(), or another conversion function when you need a specific type. Without conversion, the value is always a string. Example: count = int(input("How many? ")).

  4. Use the value in your program

    Once the value is stored and converted, use it like any other variable — in calculations, conditions, or print statements. For example: print(f"You ordered {count} items.") or if count > 10: print("Bulk discount applied.").

Python input() summary points

  1. input() always returns a str, regardless of what the user types. Never assume the returned value is a number.
  2. Pass a string argument to input() to display a prompt. Include a trailing space inside the string to keep the cursor separated from the prompt text.
  3. Call .strip() on the raw return value before converting it. Whitespace around a number causes int() and float() to raise ValueError even when the number itself is valid.
  4. Convert the return value with int(), float(), or other type functions when arithmetic or type-specific operations are needed. Wrap conversions in try/except ValueError whenever the user might enter unexpected text.
  5. Use a while True loop with try/except when you need to keep asking until the user provides valid input. Call break only after every conversion and range check succeeds.
  6. After converting type, validate the value against your program's constraints — for example, checking that a score is between 0 and 100, or that a menu choice is one of the allowed options.
  7. Do not use bool(input(...)) for yes/no input. Any non-empty string evaluates to True under bool(). Normalize the raw string with .strip().lower() and compare it against known values instead.
  8. Handle EOFError in any script that may run non-interactively — in a pipeline, a CI job, or a container. Without this, the program crashes silently in automated environments.
  9. Never use input() to collect passwords, tokens, or any secret. Use getpass.getpass() instead. It returns a str and works identically to input() except that it suppresses terminal echo.
  10. CPython fires two auditing events around every input() call: builtins.input before reading and builtins.input/result after. If input() behaves unexpectedly in a sandboxed or monitored environment, audit hooks are the likely cause.
  11. When the readline module is loaded, input() gains history recall and line-editing automatically. This is a platform-dependent behavior — not available on Android, iOS, or WASI.
  12. Extract repeated validation loops into a reusable helper that accepts a converter and a validator callable. This keeps individual input calls to one line and isolates the loop logic in a single testable function.
  13. Use map(int, input(...).split()) to collect multiple space-separated values in a single prompt. Wrap the result in list() when the count is variable. Catch ValueError when the format is not guaranteed.

Once you have input(), the prompt parameter, type conversion, and a re-prompt loop in place, you have the complete pattern for any interactive command-line program. The next logical step is structuring repeated input collection into helper functions — a natural move once your validation logic grows beyond a few lines.

check your understanding question 1 of 5

Certificate of Completion
Final Exam
Pass mark: 80% · Score 80% or higher to receive your certificate

Enter your name as you want it to appear on your certificate, then start the exam. Your name is used only to generate your certificate and is never transmitted or stored anywhere.

Question 1 of 10

Frequently Asked Questions

The input() function always returns a string, regardless of what the user types. If you need a number, you must explicitly convert it using int(), float(), or another type function.

Pass the message text as an argument to input(). For example: name = input("Enter your name: "). The string is displayed to the user before they type. Include a trailing space inside the string to keep the cursor separated from the colon.

Because input() returns a string. Adding or subtracting a string from a number causes a TypeError. You must convert the input first using int() or float() before performing arithmetic operations.

Wrap input() with int() or float(). For example: age = int(input("Enter your age: ")). This converts the returned string to the desired numeric type. Use float() when the value may include a decimal point.

input() returns an empty string ''. If you then try to convert that empty string to an integer with int(), Python raises a ValueError. Use a try/except block to handle this gracefully in production code.

Yes. Use the split() method on the result of input(). For example: x, y = input("Enter two numbers: ").split() collects both values at once. You can also convert each part: x, y = map(int, input("Enter two integers: ").split()).

input() works as described in Python 3. In Python 2, input() evaluated the expression typed by the user, which was a security risk. Python 2's raw_input() behaved like Python 3's input(). All modern Python development uses Python 3.

Wrap the int() or float() conversion in a try/except ValueError block. This lets you catch the error and prompt the user to try again instead of crashing the program. Combine this with a while True loop for a complete re-prompt pattern.

EOFError is raised when input() reaches the end of its input stream without reading any data. This happens when stdin is closed, when the user presses Ctrl+D on Linux/macOS or Ctrl+Z then Enter on Windows, or when a script runs in an automated environment with no attached terminal. Handle it with try/except EOFError and either exit gracefully or fall back to a default value.

Use getpass.getpass() from the standard library instead of input(). It displays a prompt but suppresses terminal echo so characters are not visible as the user types. It returns a str just like input(). Never use input() to collect passwords, API keys, or any other sensitive credentials.

Calling int() on a string with leading or trailing whitespace raises a ValueError even when the number itself is valid. For example, int(" 42 ") fails. Adding .strip() before conversion — int(input("...").strip()) — removes that whitespace and prevents unnecessary crashes from input the user never intended to include.

Use a while True loop with try/except inside. Attempt the conversion inside the try block and call break on success. The except block prints an error message and lets the loop repeat. This is the standard re-prompt pattern for interactive Python programs: the loop only exits when every validation check passes.

Do not use bool(input(...)). Any non-empty string — including the word "no" — evaluates to True under bool(). Instead, normalize the raw string with .strip().lower() and compare it against accepted values: check whether the result is in ("yes", "y") or ("no", "n"). Combine this with a while True loop to re-prompt when neither condition matches.

CPython raises two auditing events every time input() runs: builtins.input (with the prompt string) before reading, and builtins.input/result (with the returned string) after reading successfully. Security tools and runtime monitoring frameworks can register audit hooks via sys.addaudithook() to intercept or log these events without modifying application code.