Week 4: functions, indefinite loops
Functions
This functions worksheet summarizes the key information you need to know about functions and stack diagrams.
Indefinite loops
We have already learned about for
loops, which are called definite loops because they will execute for a fixed number of times. Recall that the syntax of a for
loop is:
for <variable> in <sequence>:
<statements>
Here is an example for
loop that prints the integers 0-3, each on its own line:
for i in range(4):
print(i)
Syntax and semantics of while
Today we will learn about the while
loop, which is called an indefinite loop because it will continue to execute as long as a certain condition is met.
The syntax of a while
loop is:
while <condition>:
<statements>
The semantics of a while
loop are that you enter the loop and test the <condition>
. If the <condition>
is True
, the <statements>
are executed. Then the <condition>
is tested again. As long as the <condition>
evaluates to True
, the statements will be executed. This looping process continues until the <condition>
eventually evaluates to False
.
Below is an example of a while
loop that will produce the same output as the for
loop given above.
j = 0
while j<4:
print(j)
j = j+1
When using a while
loop, you typically must do the following:
-
Initialize the loop variable (in this case
j
) -
Test something about the loop variable in the condition (
j < 4
) -
Update the loop variable inside the loop (
j = j+1
)
If you forget to do one of these steps, you will likely have some kind of error:
-
Not initializing the loop variable will generally cause a syntax error.
-
An incorrect condition may mean the loop never starts or never ends.
-
Forgetting to update the loop variable may create an infinite loop.
Infinite loops
Let’s purposefully create an infinite loop by removing the line that updates the loop variable by one each time. This snippet of code will continually print zero forever.
j = 0
while j<4:
print(j)
If your program ever enters an infinite loop, you need to know how to interrupt it. You do this by pressing the CTRL key and the C key at the same time.
When to use while
loops
A while
loop is necessary for situations where we aren’t sure how many times we’ll need to do something.
For example, when we are printing a menu for a user and want them to select one of the options. If they make a mistake and type an incorrect response, then we want to inform them and let them try again. We aren’t sure how many tries they will need to get it right. We want to keep trying until they give us a valid choice.
Another instance when a while
loop is necessary is for situations in which there is some randomness, like in a game with dice rolls.