User Guide
Table Of Contents
140
doThis2()
elif variable == 3:
doThis3()
else:
doThisInAllOtherCases()
6.4 Loops
Loops are blocks of code that repeat a sequence of Python
commands a set number times, or continually until a certain
condition is met.
There are two types of loop in Python:
There are two main ways to use a while loop.
To run something a set number of times, use a variable to keep
track of how many times the loop is run. For example:
count = 0
while (count < 5):
print("Hello")
count = count + 1
This sends the message “Hello” to the terminal while the
variable count contains a number that is less than 5. In effect, it
prints “Hello” five times.
You can also use a while loop to run code until something
happens. The example below continually prompts the user to
Loop Description
while Checks a condition in the same way as the if
statement, and then runs the code underneath if
the condition is True. Then it checks the condition
again and if it is still True, it runs the code
underneath again, and so on. The loop ends when
the condition is False.
for Runs the block of code for each item in a list or
sequence. The loop ends when there are no more
items.