Python Type Conversion

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 β€” True or False

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 + 1

We 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 + 1
print(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.

FunctionConverts 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.7
y = int(x)
print(y)

Output

3

Wait. Why 3? Why not 4?

Because int() does not round. It just chops off the decimal part. Always.

print(int(3.1)) # 3
print(int(3.9)) # 3
print(int(-3.7)) # -3

It 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)) # 4
print(round(3.1)) # 3

From string to int:

x = "25"
y = int(x)
print(y)

Output

25

Now y is a number. We can do math with it.

print(y + 5) # 30

But 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) # Works

And this also works:

x = " 25 "
y = int(x) # Works, spaces are ignored

From boolean to int:

print(int(True)) # 1
print(int(False)) # 0

Because True is 1 and False is 0.

Converting to Float β€” float()

float() converts something to a float (decimal number).

From int to float:

x = 25
y = float(x)
print(y)

Output

25.0

From string to float:

x = "3.14"
y = float(x)
print(y)

Output

3.14
x = "25"
y = float(x)
print(y)

Output

25.0

Even β€œ25” becomes 25.0. Because floats always have a decimal point.

From boolean to float:

print(float(True)) # 1.0
print(float(False)) # 0.0

Converting to String β€” str()

str() converts something to a string.

From int to string:

x = 25
y = str(x)
print(y)

Output

25

But 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.14
y = str(x)
print(y)
print(type(y))

Output

3.14
<class 'str'>

From boolean to string:

x = True
y = 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 = 25
message = "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 = 25
message = "I am " + str(age) + " years old"
print(message)

Output

I am 25 years old

That 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)) # True
print(bool(0)) # False
print(bool(5)) # True
print(bool(0.0)) # False
print(bool("hello")) # True
print(bool("")) # False

The 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 + num2
print("The sum is:", sum)

What happens if we run this?

If we enter 5 and 3, the output is:

The sum is: 53

Wait. 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 + num2
print("The sum is:", sum)

Now if we enter 5 and 3, the output is:

The sum is: 8

Because 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.5

Or if we want an integer, we convert to float first, then to int.

x = "25.5"
y = int(float(x))
print(y)

Output

25

See 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.9
y = int(x)
print(y) # 3, not 4

So what do we do? We use round() if we want rounding.

print(round(3.9)) # 4

Mistake 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 = 25
print(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.

FromToFunctionExample
floatintint()int(3.7) β†’ 3
stringintint()int("25") β†’ 25
intfloatfloat()float(25) β†’ 25.0
stringfloatfloat()float("3.14") β†’ 3.14
intstringstr()str(25) β†’ "25"
floatstringstr()str(3.14) β†’ "3.14"
anyboolbool()bool(1) β†’ True

Next, we will learn about Getting User Input so we can continue step by step.