Data Type Conversion
What is Data Type Conversion?
Data type conversion means changing a value from one data type to another. In Python, this is often called “casting.” You might need to do this when you want to use a value in a different way than it was originally stored.
For example, when you use the input() function, Python always gives you a string (text), even if the user types a number. If you want to use that number in a calculation, you need to convert it to an integer or a float.
Example:
age = input("How old are you? ") # age is a string, even if you type 25
print(age + 1) # This will cause an error!
To fix this, convert the string to an integer:
age = input("How old are you? ")
age = int(age) # Now age is an integer
print(age + 1) # This works!
Why is Data Type Conversion Important?
- It lets you use user input in calculations or comparisons.
- It helps you avoid errors when working with different types of data.
- It makes your programs more flexible and interactive.
This builds on what you learned in the Variables and Data Types guide, where you saw that variables can store different types of data, like strings, integers, and floats.
Common Type Conversion Functions
Python provides simple functions to convert between types:
| Function | Converts to… | Example | Result |
|---|---|---|---|
int(x) |
Integer | int("42") |
42 |
float(x) |
Float | float("3.14") |
3.14 |
str(x) |
String | str(100) |
"100" |
bool(x) |
Boolean | bool("hello"), bool("") |
True, False |
Examples
String to Integer:
num_str = "10"
num = int(num_str)
print(num + 5) # Output: 15
Integer to String:
score = 99
message = "Your score is " + str(score)
print(message) # Output: Your score is 99
String to Float:
height_str = "1.75"
height = float(height_str)
print(height * 2) # Output: 3.5
Float to Integer (truncates decimals):
price = 3.99
whole_price = int(price)
print(whole_price) # Output: 3
When Do You Need to Convert Types?
- When using
input()and you want a number, not a string - When combining numbers and text in a message
- When reading data from files (often comes in as strings)
- When you want to check if a value is True or False
Tips and Common Pitfalls
- Only convert when it makes sense: Trying to convert
"hello"to an integer will cause an error. - Check your data: Use
.isdigit()to check if a string contains only numbers before converting. - Remember:
input()always gives you a string
Example with input validation:
user_input = input("Enter a number: ")
if user_input.isdigit():
number = int(user_input)
print(number * 2)
else:
print("That's not a valid number!")
Summary
- Data type conversion lets you change values between types like string, integer, and float.
- It’s essential for working with user input and combining different types of data.
- Always check your data before converting to avoid errors.
For more on data types, see the Introduction to Variables and Data Types
← Back to where you were | → Start the course from the beginning
