Advertisement
🌱 Beginner

Python User Input – The input() Function Explained

Programs that can only run with hardcoded values are not very useful. The input() function lets your Python program communicate with the user — asking for information and responding to it. This is how you make your programs interactive.

⏱️ 18 min read 🎯 Beginner 📅 Updated 2026

The input() Function – Basics

The input() function pauses your program, displays a prompt, waits for the user to type something and press Enter, then returns what they typed as a string.

Python
# Basic input
name = input("What is your name? ")
print(f"Hello, {name}!")
▶ Output
What is your name? Alice Hello, Alice!

Always Returns a String – Type Conversion Required

This is the most common mistake: input() ALWAYS returns a string, even if the user types a number. You must convert it to the right type.

Python
# ❌ Bug: comparing string to integer
age = input("Enter your age: ")   # Returns "25" (string)
if age > 18:  # Error! Can't compare str > int
    print("Adult")

# ✅ Correct: convert to int first
age = int(input("Enter your age: "))  # Now it's an integer
if age > 18:
    print("Adult")
▶ Output
Adult
Advertisement

Converting Input to Different Types

Use int(), float(), or other conversion functions wrapped around input() to get the type you need.

Python
name = input("Name: ")              # str - no conversion needed
age = int(input("Age: "))            # int
price = float(input("Price: $"))     # float
active = input("Active? (y/n): ") == "y"  # bool

print(type(name), type(age), type(price), type(active))
▶ Output
<class 'str'> <class 'int'> <class 'float'> <class 'bool'>

Input Validation – Handling Bad Input

Users type unexpected things. Always validate input when your program depends on a specific format.

Python
# Keep asking until valid number given
while True:
    try:
        age = int(input("Enter age (0-120): "))
        if 0 <= age <= 120:
            break
        print("Age must be between 0 and 120.")
    except ValueError:
        print("Please enter a valid number.")

print(f"Your age is: {age}")
▶ Output
Enter age (0-120): abc Please enter a valid number. Enter age (0-120): -5 Age must be between 0 and 120. Enter age (0-120): 25 Your age is: 25

Getting Multiple Inputs

You can get multiple values in one line using split(), or ask separately.

Python
# Option 1: separate inputs
first = input("First name: ")
last = input("Last name: ")

# Option 2: one line, split by space
x, y = input("Enter two numbers (space-separated): ").split()
x, y = int(x), int(y)
print(f"Sum: {x + y}")
▶ Output
Enter two numbers (space-separated): 10 20 Sum: 30

Reading Input Safely

input() pauses the program, waits for the user to type a line, and returns it as a string (the newline stripped). Everything about robust input handling flows from that one fact.

name = input("Your name: ")        # str
qty  = int(input("How many? "))    # convert numbers explicitly

# robust: don't crash on bad input
while True:
    try:
        age = int(input("Age: "))
        break
    except ValueError:
        print("Please enter a whole number.")
TaskPattern
a numberint(input(...))
several values on one lineinput().split()
validatetry/except ValueError loop

The core gotcha (again): input is always text, so numeric input needs casting before math. Robustness: real programs never trust the user — wrap conversions in try/except so a typo shows a friendly message instead of a traceback. To read several values at once: a, b = input().split(), then cast each. For scripts that take arguments instead of interactive prompts, use sys.argv or the argparse module — cleaner for tools that run non-interactively.

🏋️ Practical Exercise

Build an interactive prompt:

  1. Ask the user for their name with input() and greet them.
  2. Ask for their birth year, convert it to an int, and print their approximate age.
  3. Read two numbers on one line using split() and print their sum.
  4. Re-prompt the user until they enter a valid number, using a loop and try/except.

🔥 Challenge Exercise

Create a simple guess-the-number game. Pick a secret number, then repeatedly use input() to read guesses. Convert each guess to an int inside a try/except so bad input is rejected gracefully, tell the player “higher” or “lower”, and count attempts until they guess correctly. Bonus: limit the player to a maximum number of tries.

📋 Summary

  • input(prompt) displays an optional prompt and reads one line from the user.
  • input() always returns a string, even when the user types digits.
  • Convert input explicitly with int() or float() before doing arithmetic.
  • Use .split() to read several values from a single line.
  • Wrap conversions in try/except ValueError and loop to re-prompt on invalid input.
  • In Python 3, input() replaced Python 2’s raw_input().

Interview Questions on User Input

  • What does the input() function return, and what type is it?
  • How do you read a number from the user?
  • How do you read multiple values from a single line of input?
  • How do you validate user input and re-prompt on errors?
  • What is the difference between input() in Python 3 and raw_input() in Python 2?
  • How do you handle a ValueError from a bad numeric input?
  • How do you provide a prompt message with input()?

FAQ

Why does input() return a string even when I type a number? +

By design, input() reads raw text and never guesses the type. To do math you must convert it yourself with int() or float(), which also gives you a clear place to validate the value.

How do I read two numbers on one line? +

Read the line, then split it: a, b = input().split() gives two strings, which you convert. A common idiom is nums = list(map(int, input().split())) to get a list of integers.

How do I keep asking until the user enters valid input? +

Put the input() and conversion inside a while True loop wrapped in try/except ValueError. On success, break; on failure, print a message and let the loop prompt again.

What replaced raw_input() from Python 2? +

Python 3’s input() behaves like Python 2’s raw_input() — it returns a string. Python 2’s old input() (which evaluated the text as code) was removed for safety.