CodeBlanks Logo Icon CodeBlanks

Type conversion

Learn type conversions with int(), str(), float().

Type conversion

Converting a value to another type is called type conversion. The functions int(), float(), str(), bool() are used:

age_str = "25"
age = int(age_str)     # 25 (int)
price = float("19.99")  # 19.99 (float)

If the conversion fails Python raises ValueError: int("text") errors. So check the data before converting.

Automatic and explicit conversion

Python converts types automatically in some operations: 5 + 2.0 → 7.0. This is implicit conversion.

In explicit conversion you call a function: int("25"). Explicit conversion is safer and clearer about intent.

When comparing mixed types prefer explicit conversion: int(user_input) > 18.

Practice Convert a string to a number

Assign "25" to age_str. Assign int(age_str) to age. Then print print(age).

Starter code

main.py
# Convert the string to a number

Sample solution

main.py
age_str = "25"
age = int(age_str)
print(age)

Expected output

25

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Convert a string to int

Question
age = ____("25")
Answer
age = int("25")

Explanation: int("25") converts the string to an integer.

2 What does int("text") do?

  • Returns 0
  • Returns None
  • Raises an error Correct answer
  • Returns an empty string

Explanation: int("text") raises ValueError.

3 Match the conversion functions

Term Meaning
int() To integer
float() To float
str() To string
bool() To boolean

All lessons in Beginner