Python User Input
User Input
Programs become far more useful when they can respond to the person using them. Instead of working only with values written into the code, an interactive program can ask for a name, a quantity, or a choice, and act on the answer.
Python reads input typed by the user at runtime with the built-in input() function.
Basic User Input
When Python reaches an input() call, the program pauses and waits. The user types something and presses Enter, and input() returns what was typed.
Example: Reading and Displaying Input
username = input()
print(f"Welcome, {username}!")
Example run (the user types Asha):
Asha
Welcome, Asha!
What happens:
input()pauses the program, showing a blinking cursor.- The user types
Ashaand presses Enter. input()returns the string"Asha", which is stored inusername.- The program continues and prints the welcome message.
Without any message, however, the user does not know what to type. That is what a prompt is for.
Using a Prompt Message
Pass a prompt string to input() to display a message before waiting for input. The user types on the same line as the prompt.
Example: Input With a Prompt
username = input("Please enter your username: ")
print(f"Hello, {username}")
Example run:
Please enter your username: asha_k
Hello, asha_k
Tip: End the prompt with a colon and a space (
": ") so the user's typing does not run into the message.
Taking Multiple Inputs
A program can ask for input as many times as needed. Python pauses at each input() call until the user responds.
Example: Multiple Inputs
city = input("Which city do you live in? ")
food = input("What is your favorite food? ")
year = input("Which year were you born? ")
print(f"You live in {city}, love {food}, and were born in {year}.")
Example run:
Which city do you live in? Chennai
What is your favorite food? Dosa
Which year were you born? 2001
You live in Chennai, love Dosa, and were born in 2001.
Reading Several Values on One Line
To let the user type several values at once, combine input() with split():
first, last = input("Enter your first and last name: ").split()
print(f"First: {first}, Last: {last}")
Example run:
Enter your first and last name: Meena Raman
First: Meena, Last: Raman
split() breaks the text into a list at each space, and the two values are unpacked into first and last. If the user types a different number of words, Python raises a ValueError.
Input Is Always a String
input() always returns a string — even if the user types a number.
age = input("Enter your age: ")
print(type(age))
Example run:
Enter your age: 25
<class 'str'>
This matters as soon as you try to calculate:
age = input("Enter your age: ")
print(age + 1)
Example run:
Enter your age: 25
TypeError: can only concatenate str (not "int") to str
age is the text "25", not the number 25, so it cannot be added to 1.
Converting Input to a Number
To perform calculations, convert the input with int() (whole numbers) or float() (decimal numbers).
radius = input("Enter the radius of the circle: ")
area = 3.14 * float(radius) ** 2
print(f"Circle area: {area:.2f}")
Example run:
Enter the radius of the circle: 5
Circle area: 78.50
What happens:
- The user types
5, andinput()returns the string"5". float(radius)converts it to the number5.0.** 2squares it (exponentiation runs before multiplication), giving25.0.3.14 * 25.0is78.5, shown as78.50by the:.2fformat.
You can also convert immediately when reading:
quantity = int(input("How many tickets? "))
print("Total:", quantity * 150)
Example run:
How many tickets? 3
Total: 450
Note: For more accurate circle calculations, use
math.piinstead of3.14.
Validating User Input
Users make mistakes: they type letters where numbers are expected, leave fields empty, or enter values out of range. If the program trusts input blindly, it can crash:
number = float(input("Enter a number: "))
Example run:
Enter a number: ten
ValueError: could not convert string to float: 'ten'
Input validation checks the data and handles problems gracefully instead of crashing.
Example: Keep Asking Until the Input Is Valid
while True:
value = input("Enter a valid number: ")
try:
number = float(value)
break
except ValueError:
print("Invalid input. Please enter a numeric value.")
print("Input accepted. Thank you!")
Example run:
Enter a valid number: abc
Invalid input. Please enter a numeric value.
Enter a valid number: 12.5
Input accepted. Thank you!
How it works:
while True:repeats until something explicitly stops the loop.float(value)tries to convert the text.- If the conversion succeeds,
breakexits the loop. - If it fails, Python raises a
ValueError, theexceptblock prints a message, and the loop asks again.
Example: Validating a Range
Checking the type is not always enough — the value must also make sense:
while True:
try:
age = int(input("Enter your age: "))
except ValueError:
print("Please enter a whole number.")
continue
if 1 <= age <= 120:
break
print("Please enter an age between 1 and 120.")
print("Age recorded:", age)
Example run:
Enter your age: -4
Please enter an age between 1 and 120.
Enter your age: 30
Age recorded: 30
The first check catches text that is not a number; the second rejects numbers that are outside the allowed range.
Cleaning Text Input
For text, strip() removes accidental spaces, and lower() makes comparisons case-insensitive:
answer = input("Continue? (yes/no): ").strip().lower()
if answer == "yes":
print("Continuing...")
else:
print("Stopped.")
Example run:
Continue? (yes/no): YES
Continuing...
Why Input Validation Matters
- Prevents runtime errors — invalid data does not crash the program.
- Improves the user experience — users get clear guidance instead of a traceback.
- Makes programs more reliable — calculations only run on sensible values.
- Handles unexpected behavior — real users type all kinds of things.
Common Mistakes
| Mistake | Problem |
|---|---|
| Doing math with raw input | TypeError — convert with int() or float() first |
Using int() for decimal input | int("12.5") raises ValueError; use float() |
| Not handling invalid input | The program crashes with ValueError |
| Comparing input without cleaning it | "Yes " does not equal "yes"; use strip().lower() |
| No prompt message | Users do not know what to type |
Related Concepts
- Python Type Casting — converting strings to numbers
- Python Exception Handling —
tryandexceptfor invalid input - Python while Loops — repeating a prompt until the input is valid
- Python String Methods — cleaning text input with
strip()andlower()