Chapter 6 Physical computing with Scratch and Python 149
THE OFFICIAL RASPBERRY PI BEGINNER’S GUIDE
_exit( 0 )
The indentation is important here: _exit(0) should be indented by four spaces, lining up
with else: two lines above it and if two lines above that. This instruction tells Python to
stop the program after the first button is pressed, meaning the player whose button is pressed
second doesn’t get any reward for losing!
Your finished program should look like this:
from gpiozero import LED, Button
from time import sleep
from random import uniform
from os import _exit
left_name = input("Left player name is ")
right_name = input ("Right player name is ")
led = LED( 4 )
right_button = Button( 15 )
left_button = Button( 14 )
led.on()
sleep(uniform( 5 , 10 ))
led.off()
def pressed(button):
if button.pin.number == 14 :
print(left_name + " won the game")
else:
print(right_name + " won the game")
_exit( 0 )
right_button.when_pressed = pressed
left_button.when_pressed = pressed
Click the Run button, enter the players’ names, wait for the LED to go off, and you’ll see the
name of the winning player. You’ll also see two lines from Python itself: the first, Backend
terminated (returncode: 0), is Python telling you that it received your _exit(0)
command and quit the program; the second, Resetting ..., warns you that the program
state is being reset – which is why you’ll see the list of variables disappear from the variables
area in the Thonny window (Figure 6-8, overleaf).