Python

Python Basics

Data Structures in Python

Python Core Concepts

Python Collections

Python Programs

Type Conversion and Casting


Understanding type conversion is essential because incorrect type handling can lead to runtime errors, unexpected results, and data loss. This guide will cover implicit and explicit type conversion, their functions, best practices, and real-world use cases.


1. What is Type Conversion?

Type conversion refers to changing the data type of a variable. Python provides two types of type conversion:

  1. Implicit Type Conversion (Automatic)
  2. Explicit Type Conversion (Manual or Type Casting)

Each has its specific use cases, advantages, and limitations.


2. Implicit Type Conversion (Automatic)

Python automatically converts one data type to another without explicit instruction. This is known as implicit type conversion.

Example 1: Integer to Float Conversion

num_int = 10      # Integer
num_float = 3.5   # Float

result = num_int + num_float  
print(result)  # Output: 13.5
print(type(result))  # Output: <class 'float'>

✅ Here, Python automatically converts num_int (integer) to a float before performing addition, avoiding data loss.

Example 2: Integer to Complex Number Conversion

num = 5
complex_num = num + 2j  # Complex number

print(complex_num)  # Output: (5+2j)
print(type(complex_num))  # Output: <class 'complex'>

✅ Python implicitly converts the integer 5 into a complex number for seamless computation.

When Does Python Perform Implicit Conversion?

  • When combining integers and floats → Result is a float
  • When combining integers and complex numbers → Result is a complex number
  • When handling boolean values in arithmetic operations

Example 3: Boolean in Arithmetic Operations

print(True + 5)   # Output: 6 (True is treated as 1)
print(False + 10) # Output: 10 (False is treated as 0)

✅ Python converts True to 1 and False to 0, making mathematical operations possible.

⚠️ Limitations of Implicit Conversion

  • Python does not automatically convert a string to an integer or float.
  • Python does not convert a complex number to any other type.

3. Explicit Type Conversion (Type Casting)

When Python does not automatically convert types, we need to manually convert them using built-in functions. This is called explicit type conversion or type casting.

Common Type Casting Functions in Python

FunctionConverts To
int(x)Converts x to an integer
float(x)Converts x to a floating-point number
str(x)Converts x to a string
bool(x)Converts x to a boolean (True or False)
complex(x)Converts x to a complex number
list(x)Converts x to a list
tuple(x)Converts x to a tuple

4. Converting Between Different Data Types

1. Converting String to Integer

num_str = "100"
num_int = int(num_str)

print(num_int)  # Output: 100
print(type(num_int))  # Output: <class 'int'>

int() converts the string "100" into an integer.

⚠️ If the string contains non-numeric characters, it will raise an error:

num_str = "100abc"
num_int = int(num_str)  # ValueError: invalid literal for int()

2. Converting Integer to String

num = 123
num_str = str(num)

print(num_str)  # Output: "123"
print(type(num_str))  # Output: <class 'str'>

str() converts an integer into a string, allowing concatenation with text.

age = 25
print("My age is " + str(age))  # Output: My age is 25

⚠️ Without str() conversion, this would raise an error:

print("My age is " + age)  # TypeError: can only concatenate str (not "int")

3. Converting Float to Integer

num_float = 9.99
num_int = int(num_float)

print(num_int)  # Output: 9
print(type(num_int))  # Output: <class 'int'>

int() removes the decimal part without rounding (it truncates).

⚠️ For rounding, use round() instead:

print(round(9.99))  # Output: 10

4. Converting List to Tuple and Vice Versa

my_list = [1, 2, 3]
my_tuple = tuple(my_list)

print(my_tuple)  # Output: (1, 2, 3)
print(type(my_tuple))  # Output: <class 'tuple'>

✅ Useful when you want to prevent modification of data.

my_tuple = (4, 5, 6)
my_list = list(my_tuple)

print(my_list)  # Output: [4, 5, 6]

list() allows you to modify elements.


5. Converting Boolean Values

print(int(True))  # Output: 1
print(int(False))  # Output: 0
print(bool(1))  # Output: True
print(bool(0))  # Output: False

Any non-zero value is True, and 0 is False.


6. Real-World Use Cases of Type Conversion

1. User Input Handling

age = input("Enter your age: ")  # Always returns a string
age = int(age)  # Convert to integer for calculations

print("You will be", age + 5, "years old in 5 years.")

input() always returns a string, so we convert it to an integer.


2. Data Processing

In data science, converting strings to numbers is essential for calculations.

import pandas as pd

data = {"age": ["25", "30", "35"], "salary": ["50000", "60000", "70000"]}
df = pd.DataFrame(data)

df["age"] = df["age"].astype(int)  # Convert to integer
df["salary"] = df["salary"].astype(float)  # Convert to float

Ensures numerical operations work correctly.