What is type conversion in Python?

In Python, type conversion is the process of converting data from one type to another. This is particularly useful when working with different types of data and when a specific data type is required for certain operations.

Let’s take a look at an example: Trees are felled to give us timber, which is converted into beautiful furniture for use in our homes. Imagine taking a nap on a tree trunk—very uncomfortable, right? However, when the tree trunk is transformed into a nice comfy chair, it serves a more useful purpose. Or imagine you’re developing an e-commerce app where users input quantities as text. Type conversion allows you to transform these inputs into numbers, ensuring accurate calculations for totals and payments.

Every value in Python has a data type. This specific classification helps us know how we can work with them, which is very important.

Why type conversion is necessary?

Type conversion is necessary because different data types support different operations. In Python, each data type has specific behaviors, limitations, and ways of interacting with other data types. By converting data to the required type, we ensure compatibility and accuracy in operations, making our code efficient and error-free.

For instance, if a user enters their age as a string (like “25”), we can’t perform arithmetic on it until it’s converted into an integer. Type conversion helps us bridge these differences, enabling seamless interactions between various data types and allowing our programs to work as expected.

How many data types do you know? Let’s recap:

  • Numbers: Numbers can be grouped into Integers (positive and negative whole numbers), Floating-point numbers (decimals), and Complex numbers (real and imaginary numbers).

  • Boolean: It is a value of either True or False represented by 1 or 0 respectively.

  • Strings: Strings are characters enclosed in quotation marks.

Data types in Python
Data types in Python

Python primitive versus non-primitive data structures

Before diving into type conversion, it's essential to understand the difference between primitive and non-primitive data structures in Python.

In Python, there are two types of data type conversion namely:

  • Implicit type conversion
  • Explicit type conversion (also known as type casting)

Implicit type conversion

Python performs implicit type conversion automatically at runtime when combining compatible types to avoid data loss.

For example, adding an integer to a float will result in a float. Python automatically converts the result to a float because if the result was an integer, the decimal aspect would have to be excluded resulting in data loss.

num_int = 5
num_float = 4.5
result = num_int + num_float
print(result)

Try it out! Modify this example by adding different types (e.g., adding a string to the float) to observe any errors. This will clarify how implicit conversions work in various cases.

Here, Python converts the integer 5 into a float before adding it to 4.5. This ensures the precision of the result. However, implicit conversions can’t handle every situation, especially when types are incompatible, such as adding a string to a number. This is where explicit type conversion comes into play.

Explicit type conversion

This is also known as type casting. In explicit type conversions, programmers convert data types to a required data type with the help of some built-in functions.

Let’s take a look at a few examples:

int()

This converts a data type to an integer.

Note that a string can only be converted to an integer if the string is a number. Also, a complex number cannot be converted to an integer.

a = '33'
print(int(a)) #from a string to an integer
print(int(True)) #from a Bool to an integer
print(int(11.7)) #from a float to an integer

Try converting invalid data types, such as a string with letters, to an integer to see what error is raised. Use try/except to handle these errors and understand exception handling.

float()

This converts a data type to a floating-point number.

a = '33'
print(float(a)) #from a string to a float
print(float(False)) #from a Bool to a float
print(float(11)) #from an integer to a float

str()

This converts a data type to a string.

Python = 'The '+ str(4) + 'th week of training is intensive'
# the integer 4 was converted to a string data type
print(Python)

ord()

This converts characters to their integer Unicode values.

a = '2'
print(ord(a))
print(ord('A'))

tuple()

This converts a sequence into a tuple.

a = [1, 2, 3]
print(tuple(a))

set()

This converts a sequence into a set (unique elements).

a = [1, 2, 3, 1, 2]
print(set(a))

oct(), hex(), and bin()

This converts an integer into its octal, hexadecimal, or binary equivalent.

num = 8
print(oct(num)) # conversion to octal format
print(hex(num)) # conversion to hexadecimal format
print(bin(num)) # conversion to binary format

Experiment with the code!

Attempt converting the integer to hex and then hex to binary at the same time and see how the code responds.

Edge cases

Some conversions are straightforward, while others might fail or result in unexpected outputs. For instance:

  • Converting non-numeric strings to integers will raise an error.

  • Converting floats to integers results in data loss as the decimal part is discarded.

Challenge: Summing numeric values

Given a list of mixed data types that includes integers, floats, and numeric strings, write a function sum_numeric_values that:

  1. Converts all numeric values (integers, floats, and strings containing whole numbers) to floats.

  2. Sums up only the values that can be directly converted to floats without any special conditions.

  3. Ignores non-numeric strings.

Sample input

values = [10, "20", 3.5, "hello", 5, "15"]

Expected output

53.5 # Sum of the numeric values: 10 + 20 + 3.5 + 5 + 15
def sum_numeric_values(values):
pass # write your code here

After trying it yourself first, refer to the given solution by pressing the "Run" button if you're stuck.

Key takeaways

  • Type conversion: The process of converting one data type into another, either implicitly (automatic) or explicitly (manual).

  • Implicit type conversion: Python automatically handles this when performing operations between different data types, like adding an integer to a float. It ensures no data loss occurs.

  • Explicit type conversion (type casting): Programmers manually convert one data type into another using functions like int(), float(), and str(). This gives control over the conversion process.

  • Common type conversion functions:

    • int(): Converts to an integer.

    • float(): Converts to a float.

    • str(): Converts to a string.

    • ord(): Converts a character to its Unicode integer value.

  • Data loss risks: Some conversions may result in data loss, such as converting a float to an integer, which discards the decimal part.

Become a Python developer with our comprehensive learning path!

Ready to kickstart your career as a Python Developer? Our Become a Python Developer path is designed to take you from your first line of code to landing your first job.

This comprehensive journey offers essential knowledge, hands-on practice, interview preparation, and a mock interview, ensuring you gain practical, real-world coding skills. With our AI mentor by your side, you’ll overcome challenges with personalized support, building the confidence needed to excel in the tech industry.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


Why do we need explicit type conversion in Python?

Explicit type conversion is necessary when the data types are incompatible or when specific data processing requires a particular type.


What is the difference between type conversion and type coercion in Python?

  • Type conversion refers to the process of changing a data type either implicitly (handled automatically by Python) or explicitly (manually done by the programmer).

  • Type coercion is a form of implicit type conversion where Python automatically converts one data type to another during operations involving mixed types, such as adding an integer to a float.

What is the difference between type conversion and type casting in Python?

  • Type conversion is a broader term that includes both implicit (automatic) and explicit (manual) conversions between data types.

  • Type casting refers specifically to explicit type conversion, where the programmer uses functions like int(), float(), or str() to manually convert data types.

What happens when Python can’t convert types implicitly?

Python raises a TypeError, as it’s unable to reconcile incompatible types without explicit instructions.


What happens when converting a float to an integer?

The decimal part is truncated, potentially leading to data loss.


Free Resources