int/float conversion
- Python course
- Beginner
- Lesson 95/116
- 5 min
Learn safe conversion with int(input()) and float(input()).
int() and float() conversion
Because input() returns a string, you must convert it to a number for arithmetic. int() converts to an integer, float() to a decimal:
age = int(input("Yaş: "))
price = float(input("Fiyat: "))
print(age * 2) # 36
print(price + 1) # 11.5The content must be a valid numeric string. If it contains non-numeric characters, it raises ValueError.
This pattern — input followed by conversion — is standard for numeric input.
Conversion errors
If a string cannot be parsed as a number, a ValueError is raised. For example int("abc") or int("3.14") fail — int("3.14") does not work because the dot is not part of integer syntax:
int("abc") # ValueError
int("3.14") # ValueError
float("3.14") # 3.14 — OK
int("42") # 42 — OKTo convert a decimal string safely, first use float(), then int(). To catch bad input, the conversion must be wrapped in a guard block; this is covered later.
Practice Read price and double it
Assign float(input("Fiyat: ")) to price. The user types 10. Then print the doubled price with print(price * 2).
Starter code
# read the price with float
# double it and printSample solution
price = float(input("Fiyat: "))
print(price * 2)Expected output
Fiyat: 20.0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the int conversion
age = ____(input("Yaş: "))
age = int(input("Yaş: "))
Explanation: int(input(...)) converts the input to an integer.
2 Match conversions
| Term | Meaning |
|---|---|
int("42") |
42 |
float("3.14") |
3.14 |
int("abc") |
ValueError |
float("42") |
42.0 |
3 What does float('42') return?
- 42.0 (float) Correct answer
- 42 (int)
- '42' (string)
- ValueError
Explanation: float() converts a valid numeric string to a decimal.