Basic while loop
Below you can find the example from the video where the error variable, initially equal to 50.0, is divided by 4 and printed out on every run:
error = 50.0
while error > 1 :
error = error / 4
print(error)
This example will come in handy, because it's time to build a while loop yourself! We're going to code a while loop that implements a very basic control system for an inverted pendulum. If there's an offset from standing perfectly straight, the while loop will incrementally fix this offset.
Note that if your while loop takes too long to run, or your session is expiring, you might have created an infinite loop. In particular, remember to indent the contents of the loop using four spaces or auto-indentation, and make sure the conditions are such that the loop has a stopping point.
Diese Übung ist Teil des Kurses
Intermediate Python
Anleitung zur Übung
- Create the variable
offsetwith an initial value of8. - Code a
whileloop that keeps running as long asoffsetis not equal to0. Inside thewhileloop:- Print out the sentence
"correcting...". - Next, decrease the value of
offsetby 1. You can do this withoffset = offset - 1. - Finally, still within your loop, print out
offsetso you can see how it changes.
- Print out the sentence
Interaktive Übung
Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.
# Initialize offset
# Code the while loop