Bird
0
0

You want to count how many times a button is pressed using a callback. Which code snippet correctly updates a counter variable?

hard📝 Application Q8 of 15
Raspberry Pi - gpiozero Library

You want to count how many times a button is pressed using a callback. Which code snippet correctly updates a counter variable?

from gpiozero import Button
count = 0
button = Button(6)
def increment():
    global count
    count += 1
button.when_pressed = increment
input('Exit')
AFails because increment() is not called
BFails because count is not declared global
CCorrectly counts presses using global variable
DFails because button pin is invalid
Step-by-Step Solution
Solution:
  1. Step 1: Check variable scope

    Using global count inside increment allows modifying the outer count variable.
  2. Step 2: Confirm callback updates count

    Each button press calls increment, increasing count by 1.
  3. Final Answer:

    Correctly counts presses using global variable -> Option C
  4. Quick Check:

    Use global to modify outer variable in callback [OK]
Quick Trick: Use global keyword to update outer variables in callbacks [OK]
Common Mistakes:
  • Not declaring global count
  • Expecting callback to run without assignment
  • Wrong pin number assumptions

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Raspberry Pi Quizzes