Bird
0
0

This code tries to use a rule-based system but has a bug:

medium📝 Analysis Q14 of 15
AI for Everyone - What is Artificial Intelligence
This code tries to use a rule-based system but has a bug:
rules = {'hot': 'turn_on_ac', 'cold': 'turn_on_heater'}
def apply_rule(temp):
    if temp > 25:
        return rules['hot']
    elif temp <= 25:
        return rules['cold']
print(apply_rule(25))

What is the bug and how to fix it?
ABug: 'elif' should be 'else'; fix by replacing 'elif' with 'else'.
BBug: Missing rule for temp=25; fix by adding 'temp == 25' rule.
CBug: KeyError on 'cold'; fix by adding 'cold' key to rules.
DBug: Function does not return anything; fix by adding return statement.
Step-by-Step Solution
Solution:
  1. Step 1: Identify condition overlap

    The code uses 'elif temp <= 25', but temp=25 matches this condition. However, since 'if temp > 25' fails implies 'temp <= 25', the elif is redundant.
  2. Step 2: Check if 'elif' is necessary

    Since the first condition is 'temp > 25', the else branch can cover all other cases, so 'else' is simpler and clearer.
  3. Final Answer:

    Bug: 'elif' should be 'else'; fix by replacing 'elif' with 'else'. -> Option A
  4. Quick Check:

    Use else for remaining cases [OK]
Quick Trick: Use else for all other cases, not elif [OK]
Common Mistakes:
MISTAKES
  • Thinking temp=25 is missing
  • Assuming KeyError occurs
  • Believing function lacks return

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More AI for Everyone Quizzes