Bird
0
0

What will be the output of this code snippet if an error occurs during the loop?

medium📝 Predict Output Q13 of 15
Raspberry Pi - GPIO Basics with Python
What will be the output of this code snippet if an error occurs during the loop?
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
try:
    for i in range(3):
        if i == 1:
            raise Exception('Error!')
        GPIO.output(18, GPIO.HIGH)
finally:
    GPIO.cleanup()
print('Program ended')
AProgram ended
BGPIO pins remain set high
CNo output, program hangs
DException: Error!
Step-by-Step Solution
Solution:
  1. Step 1: Analyze try block with error

    The loop raises an exception at i=1, but the finally block still runs.
  2. Step 2: Effect of finally block

    GPIO.cleanup() runs regardless, resetting pins, but since there is no except block, the exception propagates after finally, so print('Program ended') does not execute. The output is the exception message.
  3. Final Answer:

    Exception: Error! -> Option D
  4. Quick Check:

    finally runs cleanup, exception prints = B [OK]
Quick Trick: finally block runs even on errors [OK]
Common Mistakes:
  • Thinking 'Program ended' prints on error
  • Thinking pins stay set after error
  • Ignoring finally block execution

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Raspberry Pi Quizzes