Oct. 9, 2021

Originally posted: Oct. 9, 2021
Last edited: 1 year, 1 month ago

What you will learn:

In this lesson, you will learn the while statement.

What you will need:

Our Python Compiler:
https://www.aeroweb.info/python/code

Our turtle user interface:
https://www.aeroweb.info/python/turtle

What is a loop?

A loop is a repetition of a block of code for a fixed number of times. Python provides two statements for creating loops:

• while ... else statement
• for ... in statement

The syntax for the while ... else statement looks like this:

``````                               while boolean_expression:
... block
else:
... block

``````

A Boolean value is either True or False.

NOTE: The else_ part is OPTIONAL and used only if needed.

How this while statement works?

As long as the boolean_expression is True, the while block is executed. If the boolean_expression becomes False, the while loop
terminates, and if the optional else is present, its block is executed.

The else part

There are 3 cases where the else statement is not executed:

• If the loop is broken out of due to a break statement, or
• If the loop is broken out of due to a return statement (if we write the loop inside a function or method), or
• If an exception is raised

NOTE: The behavior of else is the same in the while loops, for ... in loops, and try ... except blocks.

For this example you will use our Python Compiler located in our resources tab:

```n = 10
while n > 0:
print("my number is", n)
n-=1
else:
print("my number is", 0)```

```my number is 10
my number is 9
my number is 8
my number is 7
my number is 6
my number is 5
my number is 4
my number is 3
my number is 2
my number is 1
my number is 0```
` `

Web example using the turtle:

The turtle should draw a rectangular spiral with the help of a while loop. We will use a variable a, with an initial value 5 which is then

increased by 2 with each iteration of the loop. As long as the condition a < 200 is true, the statements in the loop block will be executed.

To make it a bit more fun, you can switch out the turtle icon for a spider.

import turtle
tina = turtle.Turtle()
tina.shape("turtle")

a = 5
while a < 200:
tina.forward(a)
tina.right(90)
a = a + 2

In this example, the turtle should produce an 8 pointed star:

import turtle
tina = turtle.Turtle()
tina.shape("turtle")

tina.pencolor('green')

for x in range(13):

tina.forward(200)
tina.left(150)