[Logo for The C Shore Landing Page]
The C Shore

More Control Logic and Loop in Python

Table of Contents

More Control and Loops in Python

If statements

Another important control structure in python is the if statement. This does something if some condition is True. In real life you might say, “If I'm late for school, then run else walk”.

In python this would be expressed as:

if late_for_school:
  run()
else:
  walk()

From our LED, buttons, and buzzers, we might say, if button is pressed, then play a sound on the buzzer, else blink LED. That would be written as:

from gpiozero import LED, Button, TonalBuzzer
from gpiozero.tones import Tone
from time import sleep

led = LED(17)
buzzer = TonalBuzzer(27)
button = Button(4)

while True:
    if button.is_pressed:
        buzzer.play("A4")
        sleep(1)
        buzzer.stop()
    else:
        led.blink()
    sleep(1)

Note the indentation. In python the indentation is part of the syntax, and is required.