Python Foundations · Lesson 3 of 12

Input and type conversion

input(), int(), float() and validation. Learn through short examples, practical tasks and targeted questions.

← All lessons

Input and conversion

input() always returns text, even if the user types digits. Programs that need to compare or calculate numerical values must convert that string using int() or float(). Test a whole number, a decimal and non-numeric input to discover when conversion can fail.

Watch out: Do not assume the user will enter a valid number: int("hello") raises a ValueError unless the program handles it.

1 · Understand

input(), int(), float() and validation. Study the code and predict what it does before running it. Change a value or string and observe how the output changes.

name = input("Your name: ")
year = int(input("Birth year: "))
print("Hello", name, "— in 2030 you will be", 2030 - year)
Download example .py ↓

2 · Practise

Ask for a distance in kilometres, convert it to miles using 0.621371 and display a rounded answer.

Plan your inputs, processing and outputs. Write the code in Mu, IDLE or PyCharm; test at least three cases.

Show a reference solution after attempting the task
km = float(input("Kilometres: "))
miles = km * 0.621371
print("Miles:", round(miles, 2))
Download reference solution .py ↓

3 · Debug the code

Identify the problem and explain how to fix it before revealing the answer.

age = input("Age: ")
print(age + 1)
Reveal the corrected program and explanation
age = int(input("Age: "))
print(age + 1)

Compare the two snippets. Identify the changed line, run the corrected version and explain the effect.

4 · Check your understanding

What does input() return before conversion?

5 · Challenge and reflect

Extension: Improve your solution to deal with unexpected input, add a second feature or display results more clearly.

Reflect: What was the hardest part? What would you test if someone else used your program?

Want extra practice? Try interactive Python tracing and debugging questions →

APPLY THE IDEA

Use this skill beyond the example

The value returned by input() is text, even if a student types digits. Predict what happens when you combine two inputs without conversion, and then compare it with adding int() values.

Quick check: Why might input("Age: ") need conversion before arithmetic?

Check: input() returns a string, so int() or another suitable conversion is needed for numerical arithmetic.