Python input() Function

Learn how Python input() works, why it returns a string, how to convert input to int or float, handle non-numeric values, validate user input, take multiple inputs, and use input with asyncio.

Published

Updated

Read time 5 min read

Reviewed byDeepak Prasad

Python input() Function

input() is Python’s standard way to read a line from the keyboard. It shows an optional prompt, waits until the user presses Enter, and returns what they typed as a str.

If you need a number, convert with int() or float(). If the user might enter invalid text, catch ValueError with try/except—or loop until the input is valid.

Tested on: Python 3.13.3; kernel 6.14.0-37-generic.


Python input() quick reference

Task Use
Take string input input("Enter your name: ")
Take integer input int(input("Enter your age: "))
Take float input float(input("Enter price: "))
Remove spaces input().strip()
Normalize yes/no input input().strip().lower()
Take multiple values input().split()
Validate numeric input try/except ValueError
Keep asking until valid while True with try/except
Async-compatible input asyncio.to_thread() or aioconsole
Hide password input getpass.getpass()

Basic syntax of input()

python
input([prompt])
  • prompt — optional string shown before input (add a trailing space so the cursor is not glued to the text).
  • Behavior — pauses the program until Enter.
  • Return value — always str (including empty string "" if the user presses Enter with no text).

See the official input() docs.


Take string input in Python

python
name = input("Enter your name: ")
print(f"Hello, {name}!")

End prompts with a space or colon plus space so output reads cleanly in the terminal.


input() always returns a string

This is the most common beginner surprise—and it matches quiz-style “age + 1” questions.

python
age = input("Enter your age: ")
print(type(age))
try:
    print(age + 1)
except TypeError as e:
    print(e)

You should see <class 'str'> and a TypeError about concatenating str and int. The user typed 25, but Python stored "25", not 25.


Take integer input using int(input())

python
age = int(input("Enter your age: "))
print("Next year, you will be " + str(age + 1) + " years old!")

Why this works:

  1. input() returns text.
  2. int() converts it to an integer.
  3. age + 1 is numeric addition.
  4. str() converts the result back for string concatenation (or use an f-string: f"Next year, you will be {age + 1} years old!").

Use int(input(...)) for age, counts, menu numbers, and quantities.


What happens if the user enters a non-numeric value?

python
age = int(input("Enter your age: "))

If the user types abc, Python raises ValueError and the program stops unless you handle it:

python
try:
    age = int(input("Enter your age: "))
except ValueError:
    print("Please enter a whole number.")

That directly answers “what if age is not numeric?”—you need validation, not bare int(input()) in production-style code. The same try / except pattern applies when reading configuration from files.


Validate numeric user input

Loop until input is valid, then optionally check a range:

python
while True:
    raw = input("Enter your age: ").strip()
    try:
        age = int(raw)
    except ValueError:
        print("That is not a valid integer.")
        continue
    if age <= 0:
        print("Age must be greater than 0.")
        continue
    break

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

Same pattern works for menu choices (1–4), quantities, and any bounded integer.


Take float input in Python

python
price = float(input("Enter price: "))
print(f"Price: {price:.2f}")

Use float() for decimals (price, height, weight, percentages). Non-numeric input still raises ValueError—wrap with try/except the same way as integers.


Take multiple inputs in one line

Space-separated:

python
parts = input("Enter two numbers: ").split()
a, b = int(parts[0]), int(parts[1])
print(a + b)

Comma-separated:

python
parts = [p.strip() for p in input("Enter values (comma-separated): ").split(",")]
print(parts)

split() returns strings—convert each part with int() or float() when needed.


Clean and normalize user input

python
answer = input("Continue? (yes/no): ").strip().lower()
if answer in ("yes", "y"):
    print("Continuing.")
elif answer in ("no", "n"):
    print("Stopping.")
else:
    print("Unknown response.")

strip() removes accidental leading/trailing spaces. lower() makes Yes, YES, and yes compare consistently.


Use input() with conditional statements

Interactive programs often combine input() with if/elif/else:

python
choice = input("What do you need? (list/set/dict/tuple): ").strip().lower()

if choice == "list":
    print("Use a list for ordered, changeable items.")
elif choice == "set":
    print("Use a set for unique items.")
elif choice == "dict":
    print("Use a dict for key-value data.")
elif choice == "tuple":
    print("Use a tuple for a fixed collection.")
else:
    print("Unknown choice.")

One prompt, one branch—typical “interactive input python” flow without building a full application around it.


Python async input with asyncio

input() is blocking. Calling it directly inside async def blocks the entire event loop—other coroutines cannot run while waiting for the keyboard.

Stdlib approach — run blocking input() in a thread:

python
import asyncio

async def ask_name() -> str:
    return await asyncio.to_thread(input, "Enter your name: ")

async def main():
    name = await ask_name()
    print(f"Hello, {name}!")

asyncio.run(main())

Alternative: loop.run_in_executor(None, input, "prompt") on older patterns.

Third-party: aioconsole provides async-friendly ainput() / aprint() when you want an API designed for asyncio.

Do not assume async def + input() alone is non-blocking—it is not.


input() vs sys.argv vs argparse

Method Use when
input() Ask the user interactively while the program runs
sys.argv Read simple command-line arguments
argparse Build a CLI with options, help, and validation
File input Read prepared data from a file

For batch data already on disk, prefer read and write CSV in Python or write to file workflows instead of typing rows at the prompt.

For script arguments at launch, see Python argparse. input() is for mid-run prompts in the terminal.


Password input in Python

Do not use input() for passwords—characters appear on screen. Use getpass.getpass() from the standard library:

python
import getpass

password = getpass.getpass("Password: ")
Output

For masked input with asterisks and platform notes, see Python password input with asterisks.


Mistakes to avoid with Python input()

  • Forgetting input() always returns a str.
  • Doing age + 1 without int() conversion.
  • Ignoring ValueError on int(input()) / float(input()).
  • Using eval(input())—never execute arbitrary user text as code.
  • Calling blocking input() directly inside async def without to_thread / executor.
  • Using input() for passwords.
  • Comparing yes/no answers without strip().lower().
  • Building shell commands from raw user strings—avoid os.system(user_text); if you must run subprocesses, use Python subprocess with subprocess.run([...]) and a fixed command plus separate arguments, not string concatenation into a shell.

Summary

input() is the standard function for console user input. It always returns a string—convert with int() or float() for numbers. Handle bad numeric input with try/except ValueError, use split() for multiple values on one line, and strip() / lower() for cleaner comparisons. In asyncio, wrap blocking input() with asyncio.to_thread() or use aioconsole. For passwords use getpass, not input(). For startup CLI flags, prefer argparse over interactive prompts.


Frequently Asked Questions

1. Does Python input() return a string or a number?

Always a string—even if the user types digits only. Use int() or float() when you need numeric types.

2. What happens if int(input()) gets non-numeric text?

Python raises ValueError. Wrap the conversion in try-except or loop until the user enters valid input.

3. Can you use input() inside async def without blocking?

No—input() blocks the event loop. Use asyncio.to_thread(input, prompt) or a library like aioconsole for async-friendly input.

4. Should you use input() for passwords?

No—characters are echoed. Use getpass.getpass() instead; see the password input article for masking options.

5. When should I use argparse instead of input()?

Use input() for interactive prompts while a program runs; use argparse or sys.argv for command-line arguments passed at startup.
Bashir Alam

Data Analyst and Machine Learning Engineer

Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in OCR, text extraction, data preprocessing, and …