Python Programming Type Conversion
Implicit & Explicit Conversion Functions

Python Type Conversion Complete Guide

Learn Python type conversion techniques: Implicit automatic conversion, explicit type casting using built-in functions, and handling conversion errors with practical examples.

Implicit

Automatic conversion

Explicit

Manual type casting

Functions

int(), float(), str()

Error Handling

Try-except blocks

What is Type Conversion?

Type conversion (also called type casting) is the process of converting a variable from one data type to another. Python supports two types of conversion: Implicit (automatic) and Explicit (manual).

Key Concept

Type conversion allows you to work with different data types together. Understanding when and how to convert types is essential for writing robust Python programs.

Implicit Conversion
  • Automatic type conversion
  • Python handles it internally
  • Only for compatible types
  • Example: int → float during arithmetic
  • No data loss (widening conversion)
Explicit Conversion
  • Manual type conversion
  • Using built-in functions
  • Required for incompatible types
  • Example: str → int using int()
  • May cause data loss
Type Conversion Process
"100"
String
int()
Conversion Function
100
Integer

String "100" is converted to integer 100 using int() function

Implicit Type Conversion

Python automatically converts one data type to another when it's safe to do so. This usually happens during operations between compatible types.

Implicit Conversion Examples
# Example 1: int to float
num_int = 10      # integer
num_float = 3.14  # float

# Python automatically converts int to float
result = num_int + num_float
print(result)              # 13.14
print(type(result))        # 

# Example 2: int to float in division
a = 5
b = 2
result = a / b            # Division always returns float
print(result)             # 2.5
print(type(result))       # 

# Example 3: bool to int in arithmetic
is_true = True    # bool (True = 1, False = 0)
is_false = False
num = 10

result1 = num + is_true   # 10 + 1 = 11
result2 = num + is_false  # 10 + 0 = 10
print(f"10 + True = {result1}")   # 11
print(f"10 + False = {result2}")  # 10

# Example 4: Complex number operations
x = 5           # int
y = 3 + 2j      # complex

result = x + y  # int converted to complex
print(result)   # (8+2j)
print(type(result))  # 
Important Notes:
  • Implicit conversion only works for compatible types
  • Python always converts to the more precise type
  • Order of precision: bool → int → float → complex
  • No data loss in implicit conversion (widening conversion)
  • Division (/) always returns float, even with integers

Implicit Conversion Rules

Operation Type 1 Type 2 Result Type Example
Arithmetic int float float 10 + 3.14 → 13.14 (float)
Arithmetic int bool int 10 + True → 11 (int)
Arithmetic float complex complex 3.14 + (2+3j) → (5.14+3j)
Division int int float 5 / 2 → 2.5 (float)
Floor Division int int int 5 // 2 → 2 (int)
Limitation: Python does NOT implicitly convert string to numeric types. You must use explicit conversion for strings.
"10" + 20 # TypeError: can only concatenate str to str

Explicit Type Conversion

Explicit conversion (type casting) is done manually using Python's built-in functions. This is required when Python cannot automatically convert between types.

Built-in Conversion Functions

Python provides several built-in functions for type conversion: int(), float(), str(), list(), tuple(), dict(), set(), bool()

int()
Convert to Integer

Converts value to integer type

int() Examples
# Convert float to int (truncates decimal)
x = int(3.14)      # 3
y = int(9.99)      # 9 (NOT 10 - truncates, not rounds)

# Convert string to int
a = int("100")     # 100
b = int("-50")     # -50
c = int("  42  ")  # 42 (spaces trimmed)

# Convert boolean to int
d = int(True)      # 1
e = int(False)     # 0

# With base parameter (convert from other bases)
hex_num = int("FF", 16)    # 255 (hexadecimal)
bin_num = int("1010", 2)   # 10 (binary)
oct_num = int("77", 8)     # 63 (octal)

# Will cause errors:
# int("hello")      # ValueError
# int("3.14")       # ValueError (use float() first)
# int([1, 2, 3])    # TypeError
float()
Convert to Float

Converts value to floating-point number

float() Examples
# Convert int to float
x = float(10)      # 10.0
y = float(-5)      # -5.0

# Convert string to float
a = float("3.14")      # 3.14
b = float("  2.5  ")   # 2.5 (spaces trimmed)
c = float("-10.75")    # -10.75
d = float("1e-3")      # 0.001 (scientific notation)

# Special float values
e = float("inf")       # inf (infinity)
f = float("-inf")      # -inf
g = float("nan")       # nan (not a number)

# Convert boolean to float
h = float(True)        # 1.0
i = float(False)       # 0.0

# Will cause errors:
# float("hello")      # ValueError
# float([1, 2, 3])    # TypeError
str()
Convert to String

Converts any value to string representation

str() Examples
# Convert numbers to string
x = str(100)        # "100"
y = str(3.14)       # "3.14"
z = str(-5.5)       # "-5.5"

# Convert boolean to string
a = str(True)       # "True"
b = str(False)      # "False"

# Convert None to string
c = str(None)       # "None"

# Convert collections to string
d = str([1, 2, 3])  # "[1, 2, 3]"
e = str((1, 2, 3))  # "(1, 2, 3)"
f = str({1, 2, 3})  # "{1, 2, 3}"
g = str({"a": 1})   # "{'a': 1}"

# str() always works - no errors!
# Useful for concatenation with strings
age = 25
message = "I am " + str(age) + " years old"
print(message)  # "I am 25 years old"
list() Function
# Convert tuple to list
list((1, 2, 3))  # [1, 2, 3]

# Convert string to list
list("hello")    # ['h', 'e', 'l', 'l', 'o']

# Convert set to list
list({1, 2, 3})  # [1, 2, 3]

# Convert dict to list (keys only)
list({"a": 1, "b": 2})  # ['a', 'b']
tuple() Function
# Convert list to tuple
tuple([1, 2, 3])  # (1, 2, 3)

# Convert string to tuple
tuple("hello")    # ('h', 'e', 'l', 'l', 'o')

# Convert set to tuple
tuple({1, 2, 3})  # (1, 2, 3)

# Convert dict to tuple (keys only)
tuple({"a": 1, "b": 2})  # ('a', 'b')
dict() Function
# Convert list of tuples
dict([("a", 1), ("b", 2)])  
# {'a': 1, 'b': 2}

# With keyword arguments
dict(a=1, b=2)  # {'a': 1, 'b': 2}

# From another dictionary
dict({"a": 1, "b": 2})  # {'a': 1, 'b': 2}
set() Function
# Convert list to set
set([1, 2, 2, 3])  # {1, 2, 3}

# Convert tuple to set
set((1, 2, 2, 3))  # {1, 2, 3}

# Convert string to set
set("hello")       # {'h', 'e', 'l', 'o'}

# Removes duplicates automatically
bool()
Convert to Boolean

Converts any value to True or False

bool() Truthy and Falsy Values
# Falsy values (convert to False)
print(bool(False))     # False
print(bool(0))         # False
print(bool(0.0))       # False
print(bool(""))        # False (empty string)
print(bool([]))        # False (empty list)
print(bool(()))        # False (empty tuple)
print(bool({}))        # False (empty dict)
print(bool(set()))     # False (empty set)
print(bool(None))      # False

# Truthy values (convert to True)
print(bool(True))      # True
print(bool(1))         # True
print(bool(-1))        # True (any non-zero number)
print(bool(3.14))      # True
print(bool("hello"))   # True (non-empty string)
print(bool([1, 2]))    # True (non-empty list)
print(bool((1, 2)))    # True (non-empty tuple)
print(bool({"a": 1}))  # True (non-empty dict)
print(bool({1, 2}))    # True (non-empty set)

Type Conversion Compatibility Table

This table shows which conversions are possible between different data types in Python.

From → To int float str list tuple dict set
int - float() str() No No No No
float int()* - str() No No No No
str int()** float()** - list() tuple() No set()
list No No str() - tuple() dict()*** set()
tuple No No str() list() - dict()*** set()
dict No No str() list()† tuple()† - set()†
set No No str() list() tuple() No -
Legend:
  • ● Success - Conversion works perfectly
  • ● Warning - Works with conditions
  • ● Error - Cannot convert directly
  • * int(float) truncates decimal (doesn't round)
  • ** String must contain valid number for int()/float()
  • *** List/tuple must contain (key, value) pairs for dict()
  • † Returns only keys (not key-value pairs)

Handling Conversion Errors

Type conversion can fail if the value cannot be converted to the target type. Always handle these errors to make your program robust.

Common Conversion Errors
# These will cause ValueError
# int("hello")      # Cannot convert text to number
# int("3.14")       # String with decimal point
# float("abc")      # Not a valid number
# int("")           # Empty string
# int("123abc")     # Contains letters

# These will cause TypeError
# int([1, 2, 3])    # Cannot convert list to int
# float((1, 2, 3))  # Cannot convert tuple to float
# list(100)         # Integer is not iterable

Safe Conversion with Try-Except

Safe Type Conversion Function
def safe_convert(value, target_type):
    """Safely convert value to target type"""
    try:
        if target_type == int:
            return int(value)
        elif target_type == float:
            return float(value)
        elif target_type == str:
            return str(value)
        elif target_type == bool:
            return bool(value)
        elif target_type == list:
            return list(value)
        elif target_type == tuple:
            return tuple(value)
        else:
            raise ValueError(f"Unsupported target type: {target_type}")
    except (ValueError, TypeError) as e:
        print(f"Conversion error: {e}")
        return None  # Or raise exception based on your needs

# Usage examples
print(safe_convert("100", int))      # 100
print(safe_convert("hello", int))    # None (prints error)
print(safe_convert("3.14", float))   # 3.14
print(safe_convert([1, 2, 3], tuple)) # (1, 2, 3)

Input Validation Pattern

User Input with Validation
def get_integer_input(prompt):
    """Get integer input from user with validation"""
    while True:
        user_input = input(prompt)
        try:
            # Try to convert to integer
            number = int(user_input)
            return number
        except ValueError:
            print(f"Error: '{user_input}' is not a valid integer. Please try again.")

def get_float_input(prompt):
    """Get float input from user with validation"""
    while True:
        user_input = input(prompt)
        try:
            # Try to convert to float
            number = float(user_input)
            return number
        except ValueError:
            print(f"Error: '{user_input}' is not a valid number. Please try again.")

# Usage
age = get_integer_input("Enter your age: ")
print(f"You entered age: {age}")

price = get_float_input("Enter price: ")
print(f"Price entered: ${price:.2f}")

Practical Type Conversion Examples

Here are real-world examples of type conversion in Python programming.

Example 1: Calculator with User Input
# Simple calculator with type conversion
print("Simple Calculator")
print("Enter two numbers")

# Get input (always returns string)
num1_str = input("Enter first number: ")
num2_str = input("Enter second number: ")

# Convert strings to floats
try:
    num1 = float(num1_str)
    num2 = float(num2_str)
    
    # Perform calculations
    print(f"\nResults:")
    print(f"{num1} + {num2} = {num1 + num2}")
    print(f"{num1} - {num2} = {num1 - num2}")
    print(f"{num1} × {num2} = {num1 * num2}")
    
    # Handle division by zero
    if num2 != 0:
        print(f"{num1} ÷ {num2} = {num1 / num2}")
    else:
        print(f"{num1} ÷ {num2} = Cannot divide by zero")
        
except ValueError:
    print("Error: Please enter valid numbers!")
Example 2: Data Processing Pipeline
# Processing user data with type conversion
def process_user_data(data_list):
    """Process list of user data strings"""
    processed_data = []
    
    for item in data_list:
        try:
            # Try to convert to appropriate type
            if item.isdigit():  # Check if it's an integer
                processed_data.append(int(item))
            elif '.' in item and item.replace('.', '', 1).isdigit():
                # Check if it's a float (one decimal point)
                processed_data.append(float(item))
            elif item.lower() in ['true', 'false']:
                # Convert string boolean to actual boolean
                processed_data.append(item.lower() == 'true')
            else:
                # Keep as string
                processed_data.append(item.strip())
        except:
            # If conversion fails, keep original
            processed_data.append(item)
    
    return processed_data

# Sample data (from CSV file or user input)
raw_data = ["25", "19.99", "True", "John", "42.5", "False", "100"]
processed = process_user_data(raw_data)

print("Original data:", raw_data)
print("Processed data:", processed)
print("\nTypes after processing:")
for item in processed:
    print(f"{item} → {type(item).__name__}")
Example 3: Type Conversion Utilities
# Useful type conversion utility functions

def to_number(value, default=0):
    """Convert any value to number if possible"""
    try:
        # Try int first
        return int(value)
    except ValueError:
        try:
            # Try float if int fails
            return float(value)
        except (ValueError, TypeError):
            return default

def string_to_list(string, delimiter=','):
    """Convert delimited string to list"""
    if not string:
        return []
    return [item.strip() for item in string.split(delimiter)]

def list_to_dict(pairs):
    """Convert list of (key, value) pairs to dictionary"""
    try:
        return dict(pairs)
    except (ValueError, TypeError):
        return {}

# Usage examples
print(to_number("100"))        # 100
print(to_number("3.14"))       # 3.14
print(to_number("abc", 999))   # 999 (default)

csv_data = "apple,banana,cherry"
print(string_to_list(csv_data))  # ['apple', 'banana', 'cherry']

key_value_pairs = [("name", "John"), ("age", 30)]
print(list_to_dict(key_value_pairs))  # {'name': 'John', 'age': 30}

Key Takeaways

  • Python supports two type conversions: Implicit (automatic) and Explicit (manual)
  • Implicit conversion happens automatically for compatible types (int→float, bool→int)
  • Explicit conversion uses built-in functions: int(), float(), str(), list(), etc.
  • int() truncates decimal (doesn't round) when converting float to int
  • str() works for all types - always returns string representation
  • Always validate user input and handle conversion errors with try-except blocks
  • Use type conversion for data processing, user input handling, and interoperability
  • Remember truthy/falsy values when using bool() conversion
Next Topics: Learn about Python Keywords & Identifiers - reserved words and naming conventions in Python