Learn with Yasir

Share Your Feedback

Find & Fix Variable Mistakes in Python | Practice & Progress

Sharpen your Python debugging skills with ‘Find & Fix’ exercises for variable mistakes—naming errors, assignment issues, scope bugs—perfect for hands-on learning!.

Topic: variables


🧪 Fix & Find Questions

🟢 Beginner Fix & Find

  1. Fix the invalid variable name:

    global-var = 10
    print(global-var)
    

    Hint: 💡 Python variable names cannot contain hyphens.

    🔍 View Issue & Fixed Solution

    Issue: Hyphens are interpreted as subtraction operators.

    ✅ Fixed Solution

    global_var = 10
    print(global_var)
    

  2. Fix the variable assignment error:

    print(message)
    message = "Hello"
    

    Hint: 💡 Variables must be defined before use.

    🔍 View Issue & Fixed Solution

    Issue: Trying to access `message` before assignment.

    ✅ Fixed Solution

    message = "Hello"
    print(message)
    

  3. Fix the None comparison:

    result = None
    if result == None:  # Works but non-idiomatic
        print("Empty")
    

    Hint: 💡 Python has a dedicated operator for `None` checks.

    🔍 View Issue & Fixed Solution

    Issue: Should use identity comparison (`is`) for `None`.

    ✅ Fixed Solution

    result = None
    if result is None:
        print("Empty")
    

🟡 Intermediate Fix & Find

  1. Fix the type confusion bug:

    price = "10"
    total = price * 2
    print(total)  # Outputs "1010" (unexpected)
    

    Hint: 💡 Strings and numbers behave differently with `*`.

    🔍 View Issue & Fixed Solution

    Issue: Dynamic typing allows the operation but produces undesired string concatenation.

    ✅ Fixed Solution

    price = 10  # or int("10")
    total = price * 2
    print(total)  # Outputs 20
    

  2. Fix the None-related crash:

    def get_user():
        return None
    
    user = get_user()
    print(user.upper())  # AttributeError
    

    Hint: 💡 Methods can't be called on `None`.

    🔍 View Issue & Fixed Solution

    Issue: Attempting to call `.upper()` on a `None` value.

    ✅ Fixed Solution

    def get_user():
        return None
    
    user = get_user()
    if user is not None:
        print(user.upper())
    else:
        print("No user found")
    

🔴 Advanced Fix & Find

  1. Fix the dynamic typing pitfall:

    def add(a, b):
        return a + b
    
    print(add(5, 3))     # 8
    print(add("5", "3")) # "53" (unexpected for numbers)
    

    Hint: 💡 The `+` operator has different behaviors per type.

    🔍 View Issue & Fixed Solution

    Issue: Function works differently with strings vs numbers.

    ✅ Fixed Solution

    def add(a, b):
        return int(a) + int(b)
    

📚 Related Resources