AjapaReporter

Home life · Updated

How to Ask a User for Input in Python (With Examples)

Time it takes2 min
Steps6in the list below
LevelEasyno special skills
Official sourcePython Software Foundationcheck it for changes

Quick answer Use the built-in input() function: name = input("What is your name? ") pauses the program, waits for the user to type, and returns what they typed as a string. Convert it with int() or float() when you need a number.

You can have a working prompt running in under two minutes, and once you know input() plus one conversion and one retry loop, you can handle almost every beginner program that reads from the keyboard. Here are the steps.

How Do You Ask for Input in Python?

  1. Open a Python file or shell. Create a file ending in .py or open the interactive prompt by typing python (or python3 on some systems) in a terminal.
  2. Write the input call. Use answer = input("Your question here: "). The text in quotes is the prompt shown to the user; it appears without a newline, so the cursor sits right after it.
  3. Store the result in a variable. Whatever the user types before pressing Enter is returned as a string, even if they typed digits, so answer holds text like "42", not the number 42.
  4. Convert to a number if you need one. Wrap the call: age = int(input("Age: ")) for whole numbers, price = float(input("Price: ")) for decimals.
  5. Use the value. Print it back or use it in a calculation, for example print("Hello, " + name) or total = price * 2.
  6. Run the program. Save the file and run it with python yourfile.py. The program stops at the input() line and waits; press Enter after typing to continue.

What Should You Check Before Running?

Two things make input code work smoothly the first time. First, run it somewhere that shows a console or terminal — a plain code editor without a run window, or an environment that only shows output, gives no place to type. Second, decide up front whether the answer should be text or a number, because that choice determines whether you convert it. If you plan to loop until the input is valid, write the prompt text once so it reads well repeated.

How Do You Keep Asking Until the Input Is Valid?

Wrap the input in a while True loop with try/except, and break out only when the value converts cleanly. This is the standard pattern for whole numbers:

while True:
    text = input("Enter your age: ")
    try:
        age = int(text)
        break
    except ValueError:
        print("That is not a whole number. Try again.")

For a yes/no answer, compare the lowercased string: if input("Continue? ").lower() in ("y", "yes"):. For a fixed set of choices, check membership: if choice in ("a", "b", "c"):, and re-prompt otherwise.

What Goes Wrong and How to Fix It

Symptom Cause Fix
ValueError: invalid literal for int() You passed text like "abc" or an empty Enter press to int() Use the try/except loop above, or strip spaces first with text.strip()
TypeError when adding input to a number input() returns a string, so "5" + 5 fails Convert with int() or float() before the arithmetic
EOFError when the program runs No keyboard is attached to the run — common in online judges or scheduled scripts Run in a real terminal, or feed input another way such as a file or command-line argument
Prompt and typed text look jumbled Missing space at the end of the prompt string End the prompt with a space: "Name: "

Which Mistakes Cause Which Problems?

Four slip-ups cover most broken beginner scripts. Calling input() twice for one answer — once to prompt and once to read — makes the program appear frozen while it waits for a second, invisible entry. Comparing the raw string to a number, as in if age > 18 without converting, raises a TypeError. Assuming the user typed what you asked, with no check, lets a stray word crash the program later. And forgetting that the trailing newline is not included — input() already strips it — leads people to call .strip() twice or slice the string unnecessarily; stripping is still useful for leading and trailing spaces.

How Do You Get Several Values at Once?

Ask for them on one line and split it. x, y = input("Two numbers: ").split() gives two strings separated by whitespace; convert each with int(x). For comma-separated input, split on the comma and strip each piece: parts = [p.strip() for p in text.split(",")]. If the user may type fewer values than you expect, the split raises a ValueError about unpacking, so wrap it in the same retry loop.

Does input() Work the Same Everywhere?

In Python 3, yes — input() always returns a string. In the old Python 2, a separate raw_input() did that job while input() evaluated the text as code, which was unsafe. Any tutorial mentioning raw_input() is written for Python 2; skip it and use input(). One environment note: in some web-based notebooks, input() pops a small dialog box instead of reading the console, but the return value behaves the same. Menu names and prompts in editors differ slightly by version, so match what your screen shows.

What About Passwords and Hidden Input?

For a password you do not want echoed to the screen, use the standard library: from getpass import getpass, then pw = getpass.getpass("Password: "). In a normal terminal the typed characters stay hidden; in some editors without a real console it falls back to visible input, so test in a terminal for the hidden behaviour. Never print the value back while testing with anything real.

Sources: Python Software Foundation. Menus and buttons can differ slightly by version. Spotted something out of date? Tell us.