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

Extras for Module 2: More Python Control

Table of Contents

Extras for Module 2: More Python Control

Challenge: Stopping loop on button press

Modify the LED blinking program from Module 1 to stop when a button is pressed.

Available conditional operators

Here is a list of conditions you can use with while (or other conditional statements that we will learn about later).

Operator Name
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to
not Boolean NOT
and Boolean AND
or Boolean OR

Ordering and Grouping conditions

When you have multiple conditions (e.g. pressed != True AND counter < 8 with a separate counter > 5 ), you may need to ensure they are grouped correctly. To do that you use parentheses ().

For example:

from gpiozero import Button
from time import sleep

pressed = False

counter = 0
button = Button(2)

while ( (button.is_pressed != True) and (counter < 8) ) or (counter < 5):
    print("hello")
    counter += 1
    sleep(1)

In this case hello is printed at least five times, or up to eight if the button is not pressed before the eight time have occurred.

For Loops

The purpose of a for loop is to repeat code a specific number of times.

In Python the range function returns a list of numbers which can be used in a for loop.

for i in range(5):
    print(i)

The output is:

0
1
2
3
4

Note that range(5) returns a list of numbers starting from 0 and stopping at 4 (1 less than 5). Sometimes it’s useful to start counting from 1 instead of 0.

for i in range(1, 6):
    print(i)

The output is:

1
2
3
4
5

Note that the second input to range needs to be 6 to keep counting up to 5.

Lists

A Python list is a type of data structure. It can hold collections of any data type, and even a mixture of data types. Here is an empty list:

an_empty_list = []

You can create a list by giving it a name and adding the items of data inside square brackets:

compass = ["north", "south", "east", "west"]

Once a list has been created, you can add more data to the list using append:

numbers = [5, 10, 15, 20]
numbers.append(25)
print(numbers)

[5, 10, 15, 20, 25]

You can get rid of a piece of data from the list using remove:

numbers.remove(5)
print(numbers)

[10, 15, 20, 25]

For With Lists

This for loop which will print each item in the animals list.

animals = ["fox", "wolf", "panda", "squirrel"]

for animal in animals:
  print(animal)

The output is:

fox
wolf
panda
squirrel

Notice that the print line of code is slightly further to the right. This is called indentation - the line is indented to show that it is inside the loop. Any lines of code inside the loop will be repeated.