Bird
Raised Fist0
Raspberry Piprogramming~20 mins

Button class with callbacks in Raspberry Pi - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Button Callback Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output when a button press triggers the callback?

Consider a Button class that calls a callback function when pressed. What will be printed when the button is pressed?

Raspberry Pi
class Button:
    def __init__(self, callback):
        self.callback = callback
    def press(self):
        self.callback()

def greet():
    print("Button pressed!")

btn = Button(greet)
btn.press()
ANo output
BError: callback not defined
CButton pressed!
DButton pressed! Button pressed!
Attempts:
2 left
💡 Hint

Think about what the press method does with the callback.

🧠 Conceptual
intermediate
1:30remaining
Which statement about callbacks in a Button class is true?

In a Button class that accepts a callback function, which of the following is true about how callbacks work?

ACallbacks can only be functions defined inside the Button class.
BThe callback function runs immediately when the Button object is created.
CThe callback function must return a value to work properly.
DThe callback function is stored and called when the button is pressed.
Attempts:
2 left
💡 Hint

Think about when the callback is executed.

🔧 Debug
advanced
2:30remaining
Why does this Button callback code raise an error?

What error does the following code raise when btn.press() is called?

Raspberry Pi
class Button:
    def __init__(self, callback):
        self.callback = callback
    def press(self):
        self.callback(self)

def greet():
    print("Hello")

btn = Button(greet)
btn.press()
ATypeError: greet() takes 0 positional arguments but 1 was given
BNameError: name 'greet' is not defined
CAttributeError: 'Button' object has no attribute 'callback'
DNo error, prints 'Hello'
Attempts:
2 left
💡 Hint

Check how the callback is called and how it is defined.

📝 Syntax
advanced
2:00remaining
Which option correctly defines a Button class with a callback that accepts an argument?

Choose the correct Button class definition where the callback function accepts the Button instance as an argument.

A
class Button:
    def __init__(self, callback):
        self.callback = callback
    def press(self):
        self.callback(self.callback)
B
class Button:
    def __init__(self, callback):
        self.callback = callback
    def press(self):
        self.callback(self)
C
class Button:
    def __init__(self, callback):
        self.callback = callback
    def press(self):
        self.callback(self, self)
D
class Button:
    def __init__(self, callback):
        self.callback = callback
    def press(self):
        self.callback()
Attempts:
2 left
💡 Hint

The callback should be called with exactly one argument: the Button instance.

🚀 Application
expert
3:00remaining
What is the output of this Button class with multiple callbacks?

Given the code below, what is printed when btn.press() is called?

Raspberry Pi
class Button:
    def __init__(self):
        self.callbacks = []
    def add_callback(self, cb):
        self.callbacks.append(cb)
    def press(self):
        for cb in self.callbacks:
            cb(self)

def cb1(btn):
    print("First callback")

def cb2(btn):
    print("Second callback")

btn = Button()
btn.add_callback(cb1)
btn.add_callback(cb2)
btn.press()
AFirst callback\nSecond callback
BFirst callback
CSecond callback\nFirst callback
DNo output
Attempts:
2 left
💡 Hint

Callbacks are called in the order they were added.

Practice

(1/5)
1.

What is the main purpose of using a Button class with callbacks in Raspberry Pi programming?

easy
A. To run specific functions automatically when the button is pressed or released
B. To make the button physically larger
C. To change the button's color on the screen
D. To connect the button to the internet

Solution

  1. Step 1: Understand what callbacks do

    Callbacks are functions that run automatically when an event happens, like pressing a button.
  2. Step 2: Connect callbacks to button actions

    The Button class uses callbacks to run code when the button is pressed or released, making the program respond to these events.
  3. Final Answer:

    To run specific functions automatically when the button is pressed or released -> Option A
  4. Quick Check:

    Callbacks run functions on events = A [OK]
Hint: Callbacks run code on button press/release events [OK]
Common Mistakes:
  • Thinking callbacks change button size or color
  • Confusing callbacks with hardware features
  • Assuming callbacks connect buttons to the internet
2.

Which of the following is the correct way to assign a function my_function to run when a button is pressed using a Button class?

button = Button(17)
# What goes here?
easy
A. button.on_press(my_function)
B. button.on_press = my_function()
C. button.on_press = my_function
D. button.on_press: my_function

Solution

  1. Step 1: Understand function assignment

    Assigning a function as a callback means giving the function name without parentheses, so it can be called later.
  2. Step 2: Check syntax for callback assignment

    Using button.on_press = my_function assigns the function correctly. Adding parentheses calls it immediately, which is wrong.
  3. Final Answer:

    button.on_press = my_function -> Option C
  4. Quick Check:

    Assign function without () for callback = A [OK]
Hint: Assign function name without () for callbacks [OK]
Common Mistakes:
  • Adding parentheses calls function immediately
  • Using parentheses like a function call in assignment
  • Using incorrect syntax like colons or parentheses
3.

What will be the output when the following code runs and the button is pressed once?

class Button:
    def __init__(self):
        self.on_press = None
    def press(self):
        if self.on_press:
            self.on_press()

def greet():
    print('Hello!')

button = Button()
button.on_press = greet
button.press()
medium
A. Hello!
B. None
C. Error: on_press is not callable
D. No output

Solution

  1. Step 1: Understand the press method

    The press method checks if on_press is set and calls it if so.
  2. Step 2: Trace the code execution

    The greet function prints 'Hello!'. It is assigned to on_press, so pressing the button calls greet and prints 'Hello!'.
  3. Final Answer:

    Hello! -> Option A
  4. Quick Check:

    Callback runs greet() printing Hello! = C [OK]
Hint: Callbacks run assigned function on press, printing output [OK]
Common Mistakes:
  • Forgetting to assign the function before pressing
  • Expecting no output if on_press is None
  • Confusing function call with function assignment
4.

Find the error in this code snippet that uses a Button class with callbacks:

class Button:
    def __init__(self):
        self.on_press = None
    def press(self):
        self.on_press()

button = Button()
button.press()
medium
A. Button class is missing the on_release callback
B. on_press is called without checking if it is None, causing an error
C. The press method should not call on_press at all
D. The button object is not created correctly

Solution

  1. Step 1: Analyze the press method

    The press method calls self.on_press() without checking if on_press is set.
  2. Step 2: Identify the error cause

    Since on_press is None by default and never assigned, calling None() causes a TypeError.
  3. Final Answer:

    on_press is called without checking if it is None, causing an error -> Option B
  4. Quick Check:

    Calling None as function causes error = B [OK]
Hint: Always check callback is set before calling it [OK]
Common Mistakes:
  • Ignoring None check before calling callback
  • Assuming on_press is set automatically
  • Thinking missing on_release causes this error
5.

You want to create a Button class that supports both on_press and on_release callbacks. Which code correctly implements this so pressing and releasing the button calls the right functions?

class Button:
    def __init__(self):
        # What should go here?
    def press(self):
        # What should go here?
    def release(self):
        # What should go here?

button = Button()
button.on_press = lambda: print('Pressed')
button.on_release = lambda: print('Released')

button.press()
button.release()
hard
A. Initialize on_press and on_release as True; check if True before calling
B. Initialize on_press and on_release to empty strings; print them in press and release
C. Do not initialize callbacks; call them directly in press and release methods
D. Initialize on_press and on_release to None; call them if set in press and release methods

Solution

  1. Step 1: Initialize callbacks properly

    Set self.on_press and self.on_release to None in __init__ to indicate no function assigned yet.
  2. Step 2: Call callbacks safely in methods

    In press and release, check if the callback is not None before calling it to avoid errors.
  3. Final Answer:

    Initialize on_press and on_release to None; call them if set in press and release methods -> Option D
  4. Quick Check:

    Initialize None and check before call = D [OK]
Hint: Set callbacks to None and check before calling [OK]
Common Mistakes:
  • Using wrong default values like empty strings or True
  • Calling callbacks without checking if assigned
  • Not supporting both press and release callbacks
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard