Python Type Conversion
Table of Contents
In the last lesson, we learned about the None data type. Now letβs learn how to convert one type of value into another.
In the last few tutorials, we learned about different types of data.
- Integers β
25 - Floats β
3.14 - Strings β
"Hello" - Booleans β
TrueorFalse
Each one has its own type. And each one behaves differently.
But here is the thing. Sometimes we have one type. And we need another type.
Maybe we have a number. But we need it as text. Or we have text. But we need it as a number.
That is where type conversion comes in.
What Is Type Conversion in Python?
Type conversion means changing one type of data into another type.
Thatβs it. Simple idea.
Like changing a shirt. Same person. Different clothes.
We have a value. We change its type. The value stays the same. But the type changes.
Why Do We Need Type Conversion?
Good question. Let me give us a real example.
Imagine we ask the user for their age.
age = input("Enter your age: ")The user types 25.
But here is the problem. input() always gives us a string. Always. Even if the user types a number.
So age is not 25 (a number). It is "25" (a string).
Now if we try to do math with it:
next_year_age = age + 1We will get an error. Because we cannot add a string and a number.
print("25" + 1) # Error!We need to convert age from a string to a number first.
age = int(input("Enter your age: "))next_year_age = age + 1print(next_year_age)Now it works. Because age is a number, not a string.
That is why we need type conversion. To change data from one type to another when we need it.
The Main Type Conversion Functions in Python
Python has built-in functions for converting between types.
| Function | Converts to |
|---|---|
int() | Integer |
float() | Float |
str() | String |
bool() | Boolean |
Let me show us each one.
Converting to Integer β int()
int() converts something to an integer.
From float to int:
x = 3.7y = int(x)print(y)Output
3Wait. Why 3? Why not 4?
Because int() does not round. It just chops off the decimal part. Always.
print(int(3.1)) # 3print(int(3.9)) # 3print(int(-3.7)) # -3It does not round. It just removes the decimal. Letβs remember that.
If we want to round, we use round() instead.
print(round(3.7)) # 4print(round(3.1)) # 3From string to int:
x = "25"y = int(x)print(y)Output
25Now y is a number. We can do math with it.
print(y + 5) # 30But careful. The string must contain a valid number.
x = "hello"y = int(x) # Error!Output
ValueError: invalid literal for int() with base 10: 'hello'We cannot convert βhelloβ to a number. It does not make sense.
But this works:
x = "25"y = int(x) # WorksAnd this also works:
x = " 25 "y = int(x) # Works, spaces are ignoredFrom boolean to int:
print(int(True)) # 1print(int(False)) # 0Because True is 1 and False is 0.
Converting to Float β float()
float() converts something to a float (decimal number).
From int to float:
x = 25y = float(x)print(y)Output
25.0From string to float:
x = "3.14"y = float(x)print(y)Output
3.14x = "25"y = float(x)print(y)Output
25.0Even β25β becomes 25.0. Because floats always have a decimal point.
From boolean to float:
print(float(True)) # 1.0print(float(False)) # 0.0Converting to String β str()
str() converts something to a string.
From int to string:
x = 25y = str(x)print(y)Output
25But wait. It looks the same. How do we know it changed?
Check the type:
print(type(x)) # <class 'int'>print(type(y)) # <class 'str'>See? Different types. Even though they look the same when printed.
From float to string:
x = 3.14y = str(x)print(y)print(type(y))Output
3.14<class 'str'>From boolean to string:
x = Truey = str(x)print(y)print(type(y))Output
True<class 'str'>Notice β True becomes "True". It looks the same. But it is now a string, not a boolean.
Why Converting to String Is Useful
Here is a common situation.
We have a number. We want to add it to a message.
age = 25message = "I am " + age + " years old"This gives an error. Because we cannot add a string and a number.
So what do we do? We convert the number to a string.
age = 25message = "I am " + str(age) + " years old"print(message)Output
I am 25 years oldThat works.
But there is a better way. We will learn about f-strings in a later tutorial. They make this much easier.
Converting to Boolean β bool()
bool() converts something to a boolean.
We learned about this in the last tutorial. But let me remind us.
print(bool(1)) # Trueprint(bool(0)) # Falseprint(bool(5)) # Trueprint(bool(0.0)) # Falseprint(bool("hello")) # Trueprint(bool("")) # FalseThe rule is simple:
- Falsy values become
False - Everything else becomes
True
Falsy values are: False, None, 0, 0.0, "", empty collections.
Everything else is truthy. And becomes True.
Python Type Conversion: A Real-Life Example
Letβs build a simple calculator.
num1 = input("Enter first number: ")num2 = input("Enter second number: ")
sum = num1 + num2print("The sum is:", sum)What happens if we run this?
If we enter 5 and 3, the output is:
The sum is: 53Wait. That is wrong. It should be 8.
Why did it give 53?
Because input() gives strings. So num1 is "5" and num2 is "3". And "5" + "3" gives "53". String concatenation, not addition.
To fix this, we need to convert them to numbers.
num1 = input("Enter first number: ")num2 = input("Enter second number: ")
num1 = int(num1)num2 = int(num2)
sum = num1 + num2print("The sum is:", sum)Now if we enter 5 and 3, the output is:
The sum is: 8Because now num1 is 5 (a number) and num2 is 3 (a number). And 5 + 3 is 8.
That is why type conversion matters. It changes how the data behaves.
Common Mistakes with Python Type Conversion
Mistake 1: Converting a String with a Decimal to Int
x = "25.5"y = int(x)This gives an error.
ValueError: invalid literal for int() with base 10: '25.5'Why? Because "25.5" is not a valid integer. It has a decimal point.
So what do we do? We use float() first.
x = "25.5"y = float(x)print(y)Output
25.5Or if we want an integer, we convert to float first, then to int.
x = "25.5"y = int(float(x))print(y)Output
25See what happened? First float("25.5") gives 25.5. Then int(25.5) gives 25.
That is how we handle strings with decimal points.
Mistake 2: Forgetting That int() Does Not Round
x = 3.9y = int(x)print(y) # 3, not 4So what do we do? We use round() if we want rounding.
print(round(3.9)) # 4Mistake 3: Trying to Convert Invalid Text
x = "hello"y = int(x) # Error!So what do we do? We make sure the string contains a valid number before converting.
Checking the Type in Python
We can always check the type of a value using type().
x = 25print(type(x)) # <class 'int'>
y = str(x)print(type(y)) # <class 'str'>
z = float(x)print(type(z)) # <class 'float'>This is useful when we are not sure what type something is.
Summary of Python Type Conversions
Let me show us a table.
| From | To | Function | Example |
|---|---|---|---|
| float | int | int() | int(3.7) β 3 |
| string | int | int() | int("25") β 25 |
| int | float | float() | float(25) β 25.0 |
| string | float | float() | float("3.14") β 3.14 |
| int | string | str() | str(25) β "25" |
| float | string | str() | str(3.14) β "3.14" |
| any | bool | bool() | bool(1) β True |
Next, we will learn about Getting User Input so we can continue step by step.