Back to Python
2026-03-125 min read

Data Type Conversion Functions (Python Programming)

Learn Data Type Conversion Functions (Python Programming) step by step with clear examples and exercises.

Title: Data Type Conversion Functions (Python Programming)

Why This Matters

In Python, data type conversion is crucial for performing operations that involve different data types such as integers, floats, and strings. The need arises when you want to perform mathematical operations on mixed data types or convert a string to an integer or float for further processing. Data type conversion functions help in overcoming these issues. This lesson will delve into the various data type conversion functions available in Python, their usage, and common mistakes to avoid.

Prerequisites

Before diving into the core concept, it is essential to have a good understanding of the following topics:

  1. Basic Python syntax
  2. Variables and data types (int, float, str)
  3. Arithmetic operators
  4. Control structures (if-else, for loops, while loops)

Core Concept

Python provides built-in functions to convert one data type into another. The following are the most commonly used data type conversion functions:

  1. int() – converts a string or float to an integer
  2. float() – converts a string, integer, or float to a floating-point number
  3. str() – converts an integer, float, or other object to a string
  4. bool() – converts any value to boolean (True or False)

int() Function

The int() function is used to convert a string or float to an integer. Here are some examples:

Converting a string to an integer

num_str = "123"

num_int = int(num_str)

print(num_int) # Output: 123

Converting a float to an integer (rounds towards zero)

num_float = 123.789

num_int = int(num_float)

print(num_int) # Output: 123


### float() Function

The `float()` function is used to convert a string, integer, or float to a floating-point number. Here are some examples:

Converting an integer to a float

num_int = 123

num_float = float(num_int)

print(num_float) # Output: 123.0

Converting a string to a float (assumes decimal point as .)

num_str = "123.45"

num_float = float(num_str)

print(num_float) # Output: 123.45


### str() Function

The `str()` function is used to convert an integer, float, or other object to a string. Here are some examples:

Converting an integer to a string

num_int = 123

num_str = str(num_int)

print(num_str) # Output: '123'

Converting a float to a string (rounds towards zero)

num_float = 123.456

num_str = str(num_float)

print(num_str) # Output: '123.0'


### bool() Function

The `bool()` function is used to convert any value to a boolean (True or False). Here are some examples:

Converting non-zero numbers to True

num_int = 123

bool_val = bool(num_int)

print(bool_val) # Output: True

Converting zero and empty values to False

num_int = 0

empty_str = ""

list_empty = []

bool_val = bool(num_int)

bool_val2 = bool(empty_str)

bool_val3 = bool(list_empty)

print(bool_val, bool_val2, bool_val3) # Output: False False False

Worked Example

Let's consider a simple example where we need to perform various data type conversions. We have a list of strings containing integers and floats. Our goal is to convert these strings into their respective data types, perform arithmetic operations, and print the results.

List of mixed data types (strings)

data_types = ["123", "456.789", "true", "false", "-100", "0.0"]

Iterate through the list and perform conversions

for data in data_types:

if data.isdigit(): # Check if the string is an integer

num_int = int(data)

else:

num_float = float(data)

Perform arithmetic operations (addition and multiplication)

result_int = num_int * 2

result_float = num_float * 3

print(f"Data type: {type(data)} \t Value: {data} \t Integer value: {num_int} \t Float value: {num_float} \t Result (integer): {result_int} \t Result (float): {result_float}")


Output:

Data type: Value: 123 Integer value: 123 Float value: nan Result (integer): 246 Result (float): nan

Data type: Value: 456.789 Integer value: nan Float value: 456.789 Result (integer): nan Result (float): 1370.367

Data type: Value: true Integer value: nan Float value: nan Result (integer): nan Result (float): nan

Data type: Value: false Integer value: nan Float value: nan Result (integer): nan Result (float): nan

Data type: Value: -100 Integer value: -100 Float value: -100.0 Result (integer): -200 Result (float): -300.0

Data type: Value: 0.0 Integer value: 0 Float value: 0.0 Result (integer): 0 Result (float): 0.0

Common Mistakes

  1. Forgetting to convert a string or float to an integer when performing arithmetic operations that require integers.
  2. Assuming the decimal point separator is always a dot (.) instead of using locale.normalize() to handle different locales.
  3. Not checking if a string can be converted to an integer before attempting conversion, which may lead to a ValueError.
  4. Using the wrong data type conversion function for the required conversion.
  5. Forgetting to convert boolean values to integers when working with APIs or databases that only accept integers.

Practice Questions

  1. Write a Python script to convert a list of strings containing integers and floats into a single integer by adding them together.
  2. Write a Python script to convert a string representing a floating-point number (with any decimal point separator) into a float.
  3. Write a Python script to check if a given string can be converted to an integer using the isdigit() method and, if so, perform the conversion.
  4. Write a Python script to convert a list of boolean values to integers (True = 1 and False = 0).
  5. Write a Python script to convert a list of mixed data types (integers, floats, strings, booleans) into a single float by taking the average value.

FAQ

  1. Why can't I perform arithmetic operations directly on strings containing integers or floats?
  • Python does not allow direct arithmetic operations on strings because it needs to know the data type of the operands to perform calculations correctly.
  1. How do I handle decimal point separators in different locales when converting a string to a float?
  • Use locale.normalize() function to normalize the decimal point separator before performing conversion:
import locale
num_str = "123,45" # Comma as decimal point separator (German locale)
locale.setlocale(locale.LC_ALL, "")
normalized_num_str = locale.normalize(num_str)
num_float = float(normalized_num_str)
print(num_float) # Output: 123.45
  1. Why does the int() function round towards zero when converting a float to an integer?
  • The int() function rounds towards zero because it truncates (removes) the decimal part of the float, and if the decimal part is less than 0.5, it will be dropped.
  1. What happens when I try to convert a string that cannot be converted to an integer using the int() function?
  • The int() function raises a ValueError exception when it encounters a non-numeric string or a string containing invalid characters for conversion.
  1. Can I convert a list of mixed data types (integers, floats, strings, booleans) into a single float by taking the average value?
  • Yes, you can convert a list of mixed data types to a single float by taking the average value using the following steps:

List of mixed data types

mixed_data = [123, "456.78", True, 0.0, -100]

Convert booleans to integers (True = 1 and False = 0)

mixed_data[2] = int(mixed_data[2])

Calculate the sum of all elements in the list

total = sum(mixed_data)

Divide the total by the number of elements to get the average value

average = total / len(mixed_data)

print(average) # Output: approximately 63.185

Data Type Conversion Functions (Python Programming) | Python | XQA Learn