Which code snippet correctly adds a random delay between 1 and 5 seconds before turning on the LED on pin 18?
hard📝 Application Q15 of 15
Raspberry Pi - LED and Button Projects
You want to improve your Raspberry Pi reaction time game by adding a random delay before lighting the LED. Which code snippet correctly adds a random delay between 1 and 5 seconds before turning on the LED on pin 18?
Aimport random
import time
wait = random.randint(1, 5)
time.sleep(wait)
GPIO.output(18, GPIO.HIGH)
Bimport random
wait = random.random(1, 5)
time.sleep(wait)
GPIO.output(18, GPIO.HIGH)
Cimport random
wait = random.randint(1, 5)
GPIO.output(18, GPIO.HIGH)
time.sleep(wait)
Dimport time
wait = random.randint(1, 5)
time.sleep(wait)
GPIO.output(18, GPIO.HIGH)
Step-by-Step Solution
Solution:
Step 1: Use random.randint for integer delay
random.randint(1, 5) returns an integer between 1 and 5 seconds.
Step 2: Sleep before turning LED on
time.sleep(wait) pauses the program before GPIO.output(18, GPIO.HIGH) lights the LED.
Final Answer:
import random
import time
wait = random.randint(1, 5)
time.sleep(wait)
GPIO.output(18, GPIO.HIGH) -> Option A
Quick Check:
random.randint + sleep before LED ON [OK]
Quick Trick:Sleep before LED ON using random.randint delay [OK]
Common Mistakes:
Using random.random with arguments (invalid)
Sleeping after turning LED on
Not importing random module
Master "LED and Button Projects" in Raspberry Pi
9 interactive learning modes - each teaches the same concept differently