Consider this Python code controlling an LED on a Raspberry Pi. What will it print?
class LED: def __init__(self): self.state = False def on(self): self.state = True print("LED is ON") def off(self): self.state = False print("LED is OFF") def toggle(self): if self.state: self.off() else: self.on() led = LED() led.toggle() led.toggle()
Think about what the toggle method does depending on the LED state.
The LED starts off (False). The first toggle turns it ON and prints "LED is ON". The second toggle sees it ON, so it turns OFF and prints "LED is OFF".
Given this code controlling an LED, what is the final state of the LED?
class LED: def __init__(self): self.state = False def on(self): self.state = True def off(self): self.state = False def toggle(self): self.state = not self.state led = LED() led.on() led.toggle() led.toggle() led.off() print(led.state)
Track the state changes step by step.
The LED starts off False. on() sets True. toggle() flips to False. toggle() flips to True. off() sets False. Final state is False.
What error will this code raise when calling led.blink()?
class LED: def __init__(self): self.state = False def on(self): self.state = True def off(self): self.state = False def blink(self): for _ in range(3): self.on self.off led = LED() led.blink()
Look carefully at how methods are called inside blink.
The methods on and off are referenced without parentheses, so they are not called. No error is raised; the code runs fine but the LED does not blink.
Which code snippet correctly makes the LED blink 3 times with a 1-second pause between on and off?
Remember to call methods with parentheses and place delays correctly.
Option B calls on() and off() properly with parentheses and uses time.sleep(1) after each to pause 1 second. Others either miss parentheses or have wrong delay placement.
Given this code, how many times will the LED print "LED ON"?
class LED: def __init__(self): self.state = False def on(self): if not self.state: self.state = True print("LED ON") def off(self): if self.state: self.state = False print("LED OFF") def blink(self, times): for _ in range(times): self.on() self.off() led = LED() led.blink(5) led.on() led.on()
Count each time print("LED ON") runs, including after blinking.
The blink method calls on() and off() 5 times. Each on() call turns LED ON only if it was off, so it prints "LED ON" 5 times. Then two more on() calls happen. The first prints "LED ON" because LED is off after blinking. The second on() call does not print because LED is already on. Total prints: 5 + 1 = 6.