Introduction

Hello! Today's lesson aims to decode type conversions in Python, a pivotal concept for manipulating data in programming. Our focus will be on understanding how to convert data from one type to another, such as converting a string into an integer or a float into a Boolean. For instance, consider a situation where we need to add an integer to a string. If we fail to convert the string into an integer or the integer into a string, Python will raise an error as it is incapable of performing this operation. This problem can be resolved by type conversions. We are going to guide you through the methods for performing these conversions, specifically int(), float(), str(), and bool(). Let's begin the lesson!

Why Do We Need Type Conversions?

In Python, different operations are specially designed for different data types. To illustrate, let's see what happens when we attempt to add an integer to a string without converting the respective types:

number = 5
text = "10"
result = number + text  # This will raise a TypeError
print(result)

Executing this code results in a TypeError, as Python cannot add an integer to a string. This dilemma is where type conversions come to the rescue. We can use the int() function to convert the string into an integer and then carry out the addition:

number = 5
text = "10"
result = number + int(text)
print(result)  # Outputs: 15

See? Now, the addition works perfectly fine, thanks to type conversion!

Let's Understand Type Conversions

Python provides built-in functions to facilitate type conversions: int(), float(), str(), and bool(). Let's unpack each one with an example:

First off is int(). This function can convert a string that represents an integer into an actual integer. Similarly, it can also convert a float value into an integer:

# Integer conversion
num_string = "123"
num_int = int(num_string)
print(num_int)  # Outputs: 123

# Float to integer conversion
num_float = 3.14
num_int = int(num_float)
print(num_int)  # Outputs: 3

Similarly, str(), float(), and bool() each have their uses:

# Float conversion
num2 = 7
num_float = float(num2)
print(num_float)  # Outputs: 7.0

# String conversion
num3 = 456.3
num_str = str(num3)
print(num_str)  # Outputs: "456.3"

# Boolean conversion
num4 = 0
bool_value = bool(num4)
print(bool_value)  # Outputs: False
# 0 maps to False, and every other number maps to True
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal