Type Conversion in Python
Learn to convert between different data types in Python.
Type conversion, also called type casting, is the process of changing a value from one data type to another. This is essential when working with user input, file data, or combining different types in calculations. Python provides built-in functions to convert between strings, integers, floats, and other types safely.
📚 Concepts & Theory
Why Convert Types?
User input from input() is always a string. To do math, you need to convert it to a number.
age_str = "25"
age_num = int(age_str) # Now you can do math
Common Conversion Functions:
int("42") # String to integer: 42
float("3.14") # String to float: 3.14
str(100) # Number to string: "100"
bool(1) # Number to boolean: True
list("abc") # String to list: ["a", "b", "c"]
Converting with round():
price = 19.99
whole = int(price) # Truncates: 19
rounded = round(price) # Rounds: 20
Type Checking:
x = 42
print(type(x)) # <class 'int'>
if isinstance(x, int):
print("x is an integer")
🎯 Your Challenge
Given the string variables `num1 = "15"` and `num2 = "7"`, convert them to integers, add them together, and store the result in a variable called `total`. Then convert `total` back to a string and store it in `result_str`.
📝 Starter Code
# String numbers
num1 = "15"
num2 = "7"
# Convert to integers and add
total =
# Convert result back to string
result_str =
- Use int() to convert strings to integers
- Convert BOTH strings before adding
- Use str() to convert back to string
- The result of int("15") + int("7") is 22
Solution
num1 = "15"
num2 = "7"
total = int(num1) + int(num2)
result_str = str(total)
Explanation
We use int() to convert the string numbers to integers before adding them. The sum is 22. Then we use str() to convert the integer result back to a string for result_str.
⚠️ Common Mistakes to Avoid
- Trying to add strings directly (concatenates instead of adding)
- Forgetting to convert both numbers
- Using wrong conversion function
- Not handling invalid conversion errors