Built with Tutify.io

    AIStudyLabs

    Type Conversion and Casting

    Type Conversion and Casting

    Introduction

    In real-world Python programs, you constantly move data between different types: numbers, strings, and booleans. This lesson focuses on type conversion and casting—how Python changes data types automatically (implicit conversion) and how you change them deliberately (explicit conversion). You’ll learn to:


    Implicit vs. Explicit Type Conversion

    Implicit Type Conversion (Automatic)

    Python sometimes converts values automatically when needed. This is called implicit type conversion or type promotion.

    Python mainly does this in numeric expressions where it promotes a smaller/less precise type to a more general one to avoid data loss.

    x = 5        # int
    y = 2.0      # float
    
    result = x + y    # int + float
    print(result)
    print(type(result))
    
    # Output:
    7.0
    <class 'float'>
    

    Explanation:

    Explicit Type Conversion (Casting)

    When you deliberately change the type of a value, you perform explicit type conversion, also called casting.

    You’ll use built-in functions:

    age_str = "30"
    age = int(age_str)      # '30' -> 30
    
    price_str = "19.99"
    price = float(price_str)  # '19.99' -> 19.99
    
    is_member = True
    label = str(is_member)    # True -> 'True'
    
    count = 0
    is_empty = bool(count)    # 0 -> False
    
    print(age, type(age))
    print(price, type(price))
    print(label, type(label))
    print(is_empty, type(is_empty))
    
    # Output:
    30 <class 'int'>
    19.99 <class 'float'>
    True <class 'str'>
    False <class 'bool'>
    

    Using int(), float(), str(), and bool()

    Converting to int()

    int() works well with:

    print(int("42"))      # valid
    print(int(3.99))       # 3
    
    # print(int("3.14"))  # would raise ValueError
    
    # Output:
    42
    3
    

    Converting to float()

    float() can handle:

    print(float("3.14"))   # 3.14
    print(float(10))        # 10.0
    
    # Output:
    3.14
    10.0
    

    Converting to str()

    str() is very flexible; it converts almost any object to a human-readable string.

    num = 10
    price = 4.5
    flag = False
    
    print(str(num))    # '10'
    print(str(price))  # '4.5'
    print(str(flag))   # 'False'
    
    # Output:
    10
    4.5
    False
    

    Converting to bool()

    bool() follows Python’s truthiness rules:

    print(bool(0))        # False
    print(bool(1))        # True
    print(bool(""))      # False
    print(bool("hello")) # True
    
    # Output:
    False
    True
    False
    True
    

    Automatic Conversion in Mixed-Type Expressions

    Python mostly promotes int to float in mixed numeric operations:

    a = 10      # int
    b = 3.5     # float
    c = a * b   # int * float
    
    print(c, type(c))
    
    # Output:
    35.0 <class 'float'>
    

    Numeric promotion rules you should be able to predict:

    Python does not automatically convert between numbers and strings in expressions:

    x = 5
    text = "7"
    
    # result = x + text     # This will raise TypeError
    result = x + int(text)  # Correct: convert text to int
    print(result)
    
    # Output:
    12
    

    Handling User Input with Type Conversion

    Recall that input() always returns a string. To perform arithmetic or boolean logic, you must convert it.

    Example: Numeric Input

    user_age_str = input("Enter your age: ")
    
    # Convert to int for calculations
    user_age = int(user_age_str)
    
    years_to_100 = 100 - user_age
    print(f"You will be 100 in {years_to_100} years.")
    
    # Example Output (user types 25):
    Enter your age: 25
    You will be 100 in 75 years.
    

    Example: Boolean-like Input

    Users often type yes/no, true/false, or y/n. You need to interpret these as booleans manually:

    answer = input("Do you agree? (yes/no): ").strip().lower()
    
    is_agree = answer in ("yes", "y", "true", "1")
    
    print("Agreement status:", is_agree)
    
    # Example Output (user types "Yes"):
    Do you agree? (yes/no): Yes
    Agreement status: True
    

    Explanation:


    Common TypeError Issues and How to Fix Them

    Most TypeError problems in beginners’ code come from mixing incompatible types. Learn to recognize and fix them quickly.

    1. Concatenating Strings and Numbers

    score = 10
    # print("Score: " + score)   # TypeError
    
    print("Score: " + str(score))      # Fix 1: convert number to string
    print(f"Score: {score}")           # Fix 2: use f-strings
    
    # Output:
    Score: 10
    Score: 10
    

    2. Adding Numbers and Numeric Strings

    x = 5
    y = "7"
    
    # print(x + y)        # TypeError: unsupported operand types
    
    # Fix: convert string to int or float first
    sum_int = x + int(y)
    sum_float = float(x) + float(y)
    
    print(sum_int)
    print(sum_float)
    
    # Output:
    12
    12.0
    

    3. Invalid Literal for int() or float()

    value = "10kg"
    
    # This will fail:
    # weight = int(value)   # ValueError: invalid literal for int()
    
    # Safer approach with simple validation
    numeric_part = "".join(ch for ch in value if ch.isdigit())
    if numeric_part:
        weight = int(numeric_part)
        print("Weight:", weight)
    else:
        print("No numeric value found")
    
    # Output:
    Weight: 10
    

    Key idea: Only convert strings that are valid numeric literals; otherwise, you’ll get a ValueError at runtime.


    Summary / Key Takeaways

    In this lesson on Type Conversion and Casting, you have learned:

    Python Programming – Complete Course with Practical Examples — Variables, Data Types, and Type Conversion

    Getting Started with Python and the Course

    Python Syntax, Indentation, and Core Concepts

    Variables, Data Types, and Type Conversion

    Operators, Expressions, and Control Flow

    Loops and Iteration Patterns

    Working with Strings in Depth

    Collections: Lists, Tuples, Sets, and Dictionaries

    Functions and Program Structuring

    Functional Programming Concepts in Python

    Modules, Packages, and Code Organization

    Error Handling and Debugging Fundamentals

    File Handling and Data Formats

    Object-Oriented Programming in Python

    Advanced Python: Iterators, Generators, and Decorators

    Python Standard Library for Real-World Tasks

    Python for Automation and Scripting

    Testing and Quality Assurance in Python

    Tutorial Not Found