In Python, different kinds of data exist, like numbers, text, and more. These types of data are called data types. For example:
- Integers
: Whole numbers likeint
,5
,10
-3
- Floats
: Decimal numbers likefloat
,3.14
5.0
- Strings
: Text likestr
,"hello"
"Python"
Sometimes, you might want to convert one data type to another. This process is called type conversion. Python allows you to convert data from one type to another, which can be helpful when performing operations with mixed types.
How do you convert types?
You can convert a value to a different type using type casting functions. Here are the most common ones:
: Converts a value to an integer (whole number).
x = "10"
y = int(x) # Converts string "10" to integer 10
print(y) # Output: 10
: Converts a value to a float (decimal number).
x = "3.14"
y = float(x) # Converts string "3.14" to float 3.14
print(y) # Output: 3.14
: Converts a value to a string (text).
x = 100
y = str(x) # Converts integer 100 to string "100"
print(y) # Output: "100"
Why do we need type conversion?
Sometimes, Python might automatically convert types for us, but there are cases where you might need to manually convert them. For example:
User input: When a user enters data (like from the keyboard), Python reads it as a string, even if it’s a number. So if you want to do math with it, you need to convert it to an integer or float.
age = input("Enter your age: ") # This is a string
age = int(age) # Now it's an integer, so you can use it in math
Performing operations: If you want to add a number and a string, you can’t do that directly. You might need to convert the string to a number first.
A simple example
Let’s say you want to add a number to a string that represents a number:
x = "5" # This is a string
y = 10 # This is an integer
# To add them, you need to convert the string to an integer
result = int(x) + y
print(result) # Output: 15
Summary
Type conversion helps you work with different data types by turning one type into another. It’s like changing a tool in your toolbox to fit the job you need to do! Python makes this easy with functions like int()
float()
str()