Skip to content
Laviyx Learn

Try

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.

Beginner5 min readUpdated
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#

Python
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:

Output
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#

Python
age = input("Your age: ")
print(type(age))
Output
Your age: 21
<class 'str'>

Even though the user typed digits, age is the string "21". To do maths, convert it:

Python
age = int(input("Your age: "))
print(f"Next year you will be {age + 1}")
Output
Your age: 21
Next year you will be 22

Use float() for decimals:

Python
qty = int(input("Quantity: "))
price = float(input("Price: "))
print(f"Total: {qty * price}")
Output
Quantity: 4
Price: 2.5
Total: 10.0

Cleaning up text#

Users type extra spaces and random capitalisation. strip() removes spaces at both ends, and title() capitalises each word:

Python
name = input("Name: ").strip().title()
print(f"[{name}]")
Output
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:

Python
a, b, c = map(int, input("Three numbers: ").split())
print(a + b + c)
Output
Three numbers: 3 4 5
12

When the input is invalid#

If the user types something that cannot be converted, the program crashes:

Python
age = int(input("Your age: "))
Output
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:

Python
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}")
Output
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: 30

isdigit() 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:

Output
Temperature in Celsius: 72
72.0°C is 161.6°F
Show hint

Convert the input with float(), then use an f-string with :.1f.

Show solution
Python
celsius = float(input("Temperature in Celsius: "))
fahrenheit = celsius * 9 / 5 + 32
print(f"{celsius}°C is {fahrenheit:.1f}°F")
Output
Temperature in Celsius: 72
72.0°C is 161.6°F

float() lets the user type decimals like 36.6 as well as whole numbers.

Key takeaway#

Finished this lesson?