while loops

while loops Titelbild

Over and over again

We have a small problem. Every Python program always runs from the top (first line of code) to the bottom (the last line of code). That is super cool because we know we can consistently import the libraries in the first line of code and we always know that is the first thing program will do. This however also means that it would be a lot of work if we wanted to have an LED that would remain blinking forever. To do this we would need to write a lot of code in a manner similar to below:

gpio.output(18, gpio.HIGH)
time.sleep(2)
gpio.output(18, gpio.LOW)
time.sleep(2)

Luckily someone has already created a solution for this problem. We present to you:

The while-loop

The while-loop is somewhat similar to the if-statement because they are both based on a condition. The difference is, as long as the condition is true, the while-loop will continue. If you can remember from before, the if-statement will only check the condition and execute the code once. Let’s have a look at how they appear in real life:

sun = "shining"
while sun == "shining":
     print("Let’s go to the beach")

Looks quite similar, right? There is one thing, however, that you should always keep in mind when working with a while-loop. Because the loop always repeats itself, it may be necessary for you to build a “breakout” point into the code. Without this the loop could keep running until the program is closed externally or until the Pi stops working. So in this example we need to make sure that there is a sunset. Please keep the colon : at the end of the condition in min. This is important for Python so that it knows when the condition stops and when the intended code to be executed/looped starts.

Here is one more example, this time with an LED:

import RPi.GPIO as gpio
import time

gpio.setmode(gpio.BCM)
gpio.setup(18, gpio.OUT)

blink = "yes"

while blink == "yes":
     gpio.output(18, gpio.HIGH)
     time.sleep(2)
     gpio.output(18, gpio.LOW)
     blink = input("Again? yes or no")

I hope you can imagine how cool this program is! You should know lines 1 to 5 by now. This time the variable in line 7 is quite important. If we don’t create the variable and set the variable to yes, the while-loop in line 9 would never start and the program would simply end, without anything really happening. However, because the content is “yes”, everything that is intended in the while-loop will run at least one time. In line 13 the variable blink will get new content with the input() function. Now you have the ability to decide if the LED should blink at least one more time with “yes” or if the program should stop with a “no”.

After pressing the enter key, the program starts again in line 9, and the condition blink == "yes" is tested again. This will keep on and on until the condition is no longer true.

Noch Fragen oder Feedback?

Bevor du eine Frage stellen kannst musst du dich zuerst Anmelden oder Regestrieren!