Python course menu
Python User Input: input(), Converting Numbers and Validating Answers
Learn how to read keyboard input in Python with input(): prompts, converting input to int and float, cleaning text with strip(), reading several values on one line, and validating input with a loop.
On this page
So far, every program has used values written directly in the code. input() lets a program ask the user for a value while it runs, making it interactive: a calculator, a quiz, a simple game.
Reading text#
name = input("What is your name? ")
print("Hello,", name)When you run it, the program pauses at the prompt and waits for you to type and press Enter:
What is your name? Asha
Hello, Asha- The text inside
input(...)is the prompt. End it with a space so the answer does not stick to it. - Whatever the user types is returned as a string and stored in
name.
input() always returns a string#
age = input("Your age: ")
print(type(age))Your age: 21
<class 'str'>Even though the user typed digits, age is the string "21". To do maths, convert it:
age = int(input("Your age: "))
print(f"Next year you will be {age + 1}")Your age: 21
Next year you will be 22Use float() for decimals:
qty = int(input("Quantity: "))
price = float(input("Price: "))
print(f"Total: {qty * price}")Quantity: 4
Price: 2.5
Total: 10.0Cleaning up text#
Users type extra spaces and random capitalisation. strip() removes spaces at both ends, and title() capitalises each word:
name = input("Name: ").strip().title()
print(f"[{name}]")Name: aSHA
[Asha]Other useful cleaners: .lower() (compare answers without worrying about case) and .upper().
Several values on one line#
split() breaks a string at spaces into a list. Combine it with map(int, ...) to convert every piece:
a, b, c = map(int, input("Three numbers: ").split())
print(a + b + c)Three numbers: 3 4 5
12When the input is invalid#
If the user types something that cannot be converted, the program crashes:
age = int(input("Your age: "))Your age: abc
ValueError: invalid literal for int() with base 10: 'abc'Never trust user input. A while True loop can keep asking until the answer is valid:
while True:
text = input("Enter your age: ")
if text.isdigit() and 0 < int(text) < 130:
age = int(text)
break
print("Please enter a whole number between 1 and 129.")
print(f"Thanks! Age recorded: {age}")Enter your age: abc
Please enter a whole number between 1 and 129.
Enter your age: -3
Please enter a whole number between 1 and 129.
Enter your age: 30
Thanks! Age recorded: 30isdigit() is True only when the string contains nothing but digits, so "abc" and "-3" are rejected before int() is called. For decimals and negative numbers, a try / except block is the more general approach; see Exceptions.
Common mistakes#
Practice#
Practice exercise
Write a temperature converter that asks for a temperature in Celsius and prints it in Fahrenheit with one decimal place. Formula: F = C × 9 / 5 + 32.
Example run:
Temperature in Celsius: 72
72.0°C is 161.6°FShow hint
Convert the input with float(), then use an f-string with :.1f.
Show solution
celsius = float(input("Temperature in Celsius: "))
fahrenheit = celsius * 9 / 5 + 32
print(f"{celsius}°C is {fahrenheit:.1f}°F")Temperature in Celsius: 72
72.0°C is 161.6°Ffloat() lets the user type decimals like 36.6 as well as whole numbers.
Key takeaway#
Finished this lesson?