Type Casting & Type Conversion in Python

Module 1 • Session 08 • Allocation: 1 Contact Hr

Implicit Promotion Explicit Casting Base Conversions Truthy & Falsy

Type casting (or type conversion) is the process of converting a variable or value from one data type to another. Because Python is strongly typed, it strictly enforces operation rules between types. However, Python allows both automatic (implicit) type promotions and manual (explicit) conversions using built-in constructors.

1. Implicit Type Conversion (Coercion)

In implicit type conversion, Python automatically promotes operand types during arithmetic operations to prevent data loss. The smaller or narrower data type is automatically promoted to the wider data type (e.g., int to float, or float to complex).

# Implicit Int to Float Promotion num_int = 42 # int num_float = 3.14 # float result = num_int + num_float print(f"Result Value: {result}") # Output: 45.14 print(f"Result Type : {type(result)}") # Output: # Boolean Promotion in Integer Contexts is_active = True # bool (subclass of int, True evaluates to 1) count = 10 print(f"Total: {count + is_active}") # Output: 11

2. Explicit Type Conversion Functions

Explicit type conversion is manually performed by developers using built-in constructor functions like int(), float(), str(), and bool().

Target Constructor Source Inputs Behavior / Rules
int(x, base=10) float, str, bool Truncates decimal portion of floats toward zero. Parses clean string numbers. Accepts base arguments for binary/hex strings.
float(x) int, str, bool Converts integers and numeric strings into 64-bit IEEE 754 floating-point numbers. Supports "inf" and "nan" strings.
str(x) Any Python object Calls the object's __str__() magic method to yield its human-readable text representation. Always succeeds.
bool(x) Any Python object Evaluates truthiness. Returns False for zero numbers, empty collections, and None; True otherwise.
Truncation vs. Rounding: Executing int(8.99) produces 8, not 9. If you need standard mathematical rounding, use round(8.99) or the math.floor() / math.ceil() functions.
# String to Integer & Float Conversion price_str = "199.95" quantity_str = "3" total_cost = float(price_str) * int(quantity_str) print(f"Total Cost: ${total_cost:.2f}") # Output: Total Cost: $599.85 # Base Conversions with int() binary_str = "1010" hex_str = "1A" print(f"Binary 1010 to Decimal : {int(binary_str, 2)}") # Output: 10 print(f"Hex 1A to Decimal : {int(hex_str, 16)}") # Output: 26

3. Truthy vs. Falsy Values in `bool()` Casting

In Python, every object can be tested for truth value. When passed into bool() or evaluated inside an if condition, values evaluate to either True or False.

Falsy Checklist: The following items evaluate to False when cast to bool: None, False, numeric zero (0, 0.0, 0j), empty sequences ("", [], ()), and empty mappings ({}, set()). All other values evaluate to True.
# Evaluating Truthiness empty_items = [] user_name = "Alice" print(f"bool([]): {bool(empty_items)}") # Output: False print(f"bool('Alice'): {bool(user_name)}")# Output: True print(f"bool(0): {bool(0)}") # Output: False print(f"bool(-5): {bool(-5)}") # Output: True

4. Collection Type Conversions

Python allows casting between iterable collections (lists, tuples, sets, dictionaries) to alter mutability or perform duplicate elimination.

# Deduplicating a List with set() and list() raw_tags = ["python", "code", "python", "web", "code"] unique_tags = list(set(raw_tags)) print(f"Unique Tags List: {unique_tags}") # Output: ['python', 'code', 'web'] (order may vary) # Converting List of Key-Value Tuples to Dict pair_list = [("name", "Bob"), ("role", "Admin"), ("id", 1042)] user_dict = dict(pair_list) print(f"Dictionary Result: {user_dict}") # Output: {'name': 'Bob', 'role': 'Admin', 'id': 1042}

5. Handling Conversion Errors Safely

Attempting to cast incompatible types (e.g., converting non-numeric text like "hello" to int) raises a ValueError or TypeError. Using try-except blocks ensures program reliability.

def safe_int_conversion(val, default=0): try: return int(val) except (ValueError, TypeError): print(f"Warning: Could not convert '{val}' to int. Defaulting to {default}.") return default print(f"Parsed: {safe_int_conversion('450')}") # Parsed: 450 print(f"Parsed: {safe_int_conversion('invalid')}") # Warning raised, Parsed: 0

🏋️ Try It Yourself: Practice Challenges

Challenge 1: Numeric String Cleaner & Calculator

Write a script that takes a raw currency string like " $1,249.50 ", cleans invalid non-numeric characters, casts it to float, and calculates a 10% discount.

Challenge 2: Base System Converter

Prompt the user for a hexadecimal string (e.g., "FF"), convert it to an integer using int(), and print its binary representation via bin().

Challenge 3: Robust Collection Type Transformer

Convert a user-entered comma-separated string into a set to eliminate duplicate words, then sort and convert it into a final tuple.

⚡ Interactive Sandbox (Type Casting Engine)
Console Output:
Click "Run Code" above to execute interactive casting scripts...

📝 Knowledge Check Quiz

1. What is the result of executing `int(7.89)` in Python?
2. Which of the following values evaluates to `True` when passed to `bool()`?
3. What does `int("1010", 2)` evaluate to?
Advertisement
Horizontal Ad Banner Slot (728x90 / Responsive)