Let's review another example where we would like to count the number of button presses and break out of the infinite loop when the button has received a predetermined number of presses:
i = 0
while True:
if button.is_pressed:
button.wait_for_release()
i += 1
print("Button pressed")
if i >= 10:
break
The preceding example is available for downloading along with this chapter as GPIO_button_loop_break.py.
In this example, the program checks for the state of the is_pressed variable. On receiving a button press, the program can be paused until the button is released using the wait_for_release method. When the button is released, the variable used to store the number of presses is incremented by one.
The program breaks out of the infinite loop, when the button has received 10 presses.
![](Images/add8b086-b74e-44a0-909a-a8a30662357b.png)
A red momentary push button interfaced to Raspberry Pi Zero GPIO pin 2