Lesson 6 of 30
Type Conversion - Converting Between Data Types
Sometimes you need to convert data from one type to another. Python provides built-in functions to convert between different data types.
Converting to Integer - int()
The int() function converts a value to an integer (whole number).
# Converting string to integer
age_text = "25"
age = int(age_text)
print(age + 5) # Now we can do math!
age_text = "25"
age = int(age_text)
print(age + 5) # Now we can do math!
Output:
30
30
Important: int() removes any decimal part:
price = int(9.99)
print(price) # Becomes 9, not 10
print(price) # Becomes 9, not 10
Output:
9
9
Q1: What does int(7.8) return?
A) 7
B) 8
C) 7.8
Converting to Float - float()
The float() function converts a value to a floating-point number (decimal).
# Converting string to float
height = float("5.9")
print(height * 2)
height = float("5.9")
print(height * 2)
Output:
11.8
11.8
You can also convert integers to floats:
count = float(42)
print(count) # 42.0
print(count) # 42.0
Output:
42.0
42.0
Q2: Why do we need type conversion?
A) To make code look prettier
B) To perform operations that require specific data types
C) Python requires it for all variables
Converting to String - str()
The str() function converts a value to a string (text).
# Converting number to string
score = 95
message = "Your score is " + str(score)
print(message)
score = 95
message = "Your score is " + str(score)
print(message)
Output:
Your score is 95
Your score is 95
Why? Because you cannot directly concatenate (join) strings and numbers:
# This would cause an error:
# print("I am " + 25 + " years old")
# Correct way:
print("I am " + str(25) + " years old")
# print("I am " + 25 + " years old")
# Correct way:
print("I am " + str(25) + " years old")
Q3: What happens when you try to add a string and a number without conversion?
A) Python automatically converts them
B) You get an error
C) The number becomes 0
Common Conversion Errors
Be careful! Not all conversions work:
- int("hello") - ERROR! Cannot convert text to a number
- int("3.14") - ERROR! Use float() first, then int()
- float("twenty") - ERROR! Must be a number in text form
Practice Challenge
Your Task: Create a calculator program that:
- Asks the user for two numbers (they will be strings from input())
- Converts them to floats
- Calculates the sum, difference, product, and quotient
- Prints results using str() to combine text and numbers
Key Takeaways
- int() converts to whole numbers (removes decimals)
- float() converts to decimal numbers
- str() converts to text
- input() always returns a string - convert it if you need numbers
- Cannot add strings and numbers directly
- Not all conversions are possible - check your data first
0 Comments