## Module #4

This module is designed to show you the basics of working with 'repetition structures' in Python. When you are finished with the module please visit our NYU Classes site and take the Module 04 Quiz.

### Repetition Structures and "while" Loops

When writing a program you will find that you will often need to repeat certain statements over and over again. For example, say you wanted to write a program to compute the tip on a restaurnt bill. You could easily do this for one person by doing the following:

```# get bill amount
bill = float(input("Enter bill amount: "))
rate = float(input("Enter tip rate (i.e. 0.15): "))

# calculate tip
print ("Your tip: ", bill * rate)```

However, let's say that you wanted to compute the tip amount for 3 different restaurant bills. As of right now the only way you could do this would be to copy the program you just wrote and paste it three times:

```# get bill amount (#1)
bill = float(input("Enter bill amount: "))
rate = float(input("Enter tip rate (i.e. 0.15): "))

# calculate tip (#1)
print ("Your tip: ", bill * rate)

# get bill amount (#2)
bill = float(input("Enter bill amount: "))
rate = float(input("Enter tip rate (i.e. 0.15): "))

# calculate tip (#2)
print ("Your tip: ", bill * rate)

# get bill amount (#3)
bill = float(input("Enter bill amount: "))
rate = float(input("Enter tip rate (i.e. 0.15): "))

# calculate tip (#3)
print ("Your tip: ", bill * rate)```

There are some major disadvantages to this approach. For example - what if you were asked to compute the tip for 1,000 restaurant checks? You would by copying and pasting your code all day long! And if you inadvertently made a mistake in your original program before you copied and pasted your code you would have to fix your program in multiple places. This would become an incredibly time consuming task!

One solution to this kind of problem is to take advantage of a programming technique called a "repetition structure". This involves writing your code one time and then placing it into a special statement that causes Python to repeat it as many times as necessary. Programmers usually refer to this as a "loop".

There are a few different kinds of loops in Python. This module discusses the `while` loop which is known as a “condition controlled loop” -- this means that the looping behavior of the structure is dependent on the evaluation of a condition (i.e. a Boolean expression). The syntax for a condition controlled loop is almost identical to the `if` statement that we covered in the previous module. For example:

```while condition:
print ("this will continue to print over and over again")
print ("... as long as the condition above evaluates to True")```

In Python, a `while` loop works as follows:

1. Evaluate a Boolean expression
2. If it is False, skip the block of statements associated with the while loop
3. If it is True
• Execute the block of statements associated with the while loop
• Go back to step 1

Here's what this looks like as a flowchart - note that the structure is almost identical to an `if` statement, but with a `while` loop we re-evaluate the condition being tested until it eventually evaluates to False. The trick with `while` loops is to control the condition that is being evaluated. One way to do this is to create a variable which can be used in a boolean expression to determine if a loop needs to iterate again.

Here is the "tip calculator" program written using a `while` loop:

```# set up our loop!
# first, we must make an assumption.  our assumption is that we want to
# compute the tip on a restaurant bill.  we can express this assumption
# by creating a variable that is holding a specific value (in this case
# the value is the String "yes")
# this variable is sometimes referred to as a "control variable"
compute_tips = 'yes'

# next we can ask Python to start a loop. this loop will execute as long
# as our "compute_tips" varialbe is holding the value "yes"
# note that the first time we encounter this loop the value of "compute_tips"
# will be "yes" because we set up this variable on the previous line
while compute_tips == 'yes':

# get bill amount
bill = float(input("Enter bill amount: "))
rate = float(input("Enter tip rate (i.e. 0.15): "))

# calculate tip
print ("Your tip: ", bill * rate)

# ask the user if they want to continue
compute_tips = input('Do you want to continue? Type yes or no ')

# note that we are overwriting the "compute_tips" variable on the previous line
# once we reach the end of the loop Python will jump back up to the beginning of
# the "while" loop and re-evaluate the condition.  if the user typed the word
# "yes" then the condition evalutes to True (compute_tips == 'yes') -- but if they
# type "no" (or anything else) the condition will evaluate to False and the loop
# will not execute again.

print ("thanks for using our program")```

We refer to the process of going through a loop as an “iteration,” so if a loop cycles through 5 times then we say we have “iterated” through it 5 times

The `while` loop is considered a “pre-test” loop, meaning that it only iterates upon the successful evaluation of a condition. This means that you always need to “set up” your loop prior to Python being able to work with it (i.e. setting up a control variable).

Loops are often used in conjunction with variables to control the number of times they iterate. Often we want to make changes to a variable inside of a loop (for example, to compute the running total of a series of numbers). We can do this by setting up a variable outside of our loop and then referencing that variable inside of our loop. We call these "accumulator variables." For example:

```# set up a variable
a = 0

# enter into a loop
while a < 5:

# add 1 to "a" - this is what we call a "self referential assignment"
# we are essentially adding 1 to the current value of "a" and then
# storing the result back into the variable
a = a + 1

print (a)
```

The self-referential assignment statement works as follows: Python also supports a series of "shortcuts" for self-referential assignments: `while` loops are often used because they execute an indetermintate number of times. You can cause a `while` loop to execute for a set # of times (i.e. loop exactly 5 times) by using an accumulator variable. For example:

```# set up a counter variable to keep track of
# how many times we have looped
numloops = 0

# create a loop that keeps going as long as
# our "numloops" variable is less than 5 - this will
# evaluate to True the first time we encounter the loop
while numloops < 5:

# update our "numloops" variable to make a note
# that we have looped one more time
numloops += 1

# do something
print ("Iteration #", numloops)

```

Sample Program: This program uses a "while" loop to execute a "print" statement 10 times.

Programming Challenge: Write a simple "shopping cart" program that asks the user for a series of product prices. Compute sales tax (7%) on each price and print out the new price to the user. Next, ask the user if they want to enter another price - if they do, repeat the process. If not, end the program. Here's some sample output:

```Enter an item price: 1.00
Tax on this item is 0.07 ; total price: 1.07
Enter another price? (yes or no): yes
Enter an item price: 2.00
Tax on this item is 0.14 ; total price: 2.14
Enter another price? (yes or no): yes
Enter an item price: 3.00
Tax on this item is 0.21 ; total price: 3.21
Enter another price? (yes or no): no```

Programming Challenge: Modify Challenge #1 so that your program also keeps track of the total amount spent in addition to total tax due. Here's some sample output:

```Enter an item price: 1.00
Tax on this item is 0.07 ; total price: 1.07
Enter another price? (yes or no): yes
Enter an item price: 2.00
Tax on this item is 0.14 ; total price: 2.14
Enter another price? (yes or no): yes
Enter an item price: 3.00
Tax on this item is 0.21 ; total price: 3.21
Enter another price? (yes or no): no
-------
Total amount due: 6.42
Total tax due: 0.42```
Hint: use two "accumulator variables" to keep track of the total price and total tax. Click the "Run" button to see the program in action. Click here to download a copy of the solution.

### "while" loop control

There is always a danger with `while` loops that the condition associated with the loop will never evaluate to False. If that happens, the loop will continue running forever. We call this an "infinite loop". If you do end up with an infinite loop, you can force Python to break out of it by hitting Control->C on your keyboard. Here's an example of an infinite loop:

```a = 5

# the value stored in the variable "a"
# never changes - it's always less than 10!
while a < 10:
print ("I'm looping!")```

And here's another example:

```# no way to ever get out of this loop!
# True will never be anything but True, which
# means the condition attached to this loop will
# never be False!
while True:
print ("I'm looping!")```

There are two special commands called `break` and `continue` that you can use inside of a `while` loop to further control the flow of repetition. These commands can only be used inside of a `while` loop - they won't work anywhere else in your program.

The `break` command is used to immediately end a loop. Once a `break` statement is encoutered the loop immediately stops and Python resumes execute on the line directly after the end of the loop.

Sample Program: This program uses the "break" statement to prematurely end a loop.

The `continue` command is used to cause the loop to immediately cease its current iteration and re-evaluate its condition. The `continue` command doesn't end the loop -- it simply causes the loop to "jump" to the next iteration. If the condition evaluates to True the loop iterates again, but if it evaluates to False it will not.

Sample Program: This program uses the "continue" statement to end a loop iteration when a condition is met.

Boolean variables are often used with `while` loops to control their execution. We sometimes refer to these as "flags" and we can easily check their value (`True` or `False`) to determine if we should allow a loop to continue iterating or not.

Sample Program: This program demonstrates how a Boolean variable can be used as a "flag" to control a `while` loop.

Programming Challenge: Write a program that continually asks the user for the answer to a simple math question (2 + 2). If the user answers the question correctly you should congratulate them and end the program. If they answer the question incorrectly you should re-prompt them until they answer correctly. Here's some sample output:

```What is 2+2? 3
Wrong, try again.

What is 2+2? 5
Wrong, try again.

What is 2+2? 4
Correct!```

### Color in Turtle Graphics Part 2

Note that the graphics techniques presented in this section will not run correctly using our web-based coding environment. To try any of the code samples included below simply launch IDLE on your own computer and run the code locally.

All digital color is formed by mixing together three "base" colors - red, green and blue. By varying the amount of these colors we can instruct pixels on a display to glow in any way that we want. We refer to this as RGB color (Red, Green & Blue color).

Digital designers mix together varying amounts of red, green and blue all the time to describe colors that can be used on websites, mobile applications, games, etc. For example, in Photoshop you can mix together your own color by supplying varying amounts of Red, Green and Blue using the color picker window: Constructing a color using varying amounts of Red, Green and Blue in Photoshop

We can do the same thing in Python by telling our program to mix together varying amounts of red, green and blue when drawing a shapes to the screen. This can be done by supplying three floating point numbers to the `pencolor` or `fillcolor` functions - the first number describes the percentage of red in the desired color, the second describes the percentage of green and the third describes the percentage of blue:

```# set the pen color to red
turtle.pencolor(1.0, 0, 0) # 100% red, 0% green, 0% blue

# set the pen color to green
turtle.pencolor(0, 1.0, 0) # 0% red, 100% green, 0% blue

# set the pen color to a custom color!
turtle.pencolor(0.7, 0.2, 0.5)```

Note that numbers passed to the `pencolor` function in this way must be between 0.0 and 1.0 (inclusive), where 0.0 represents none of that color and 1.0 represents all of that color. You can construct the color white by supplying 1.0 for all color values (100% red, 100% green and 100% blue) - likewise you can construct the color black by supplying 0.0 for all color values (0% red, 0% green, 0% blue).

Here's a variation of the line thickness program we've been writing that uses this technique:

```# make the turtle graphics module available
import turtle

# set up our graphical canvas
# width = 500, height = 500
turtle.setup(500, 500)

# move to the top left side of the screen
turtle.penup()
turtle.goto(-50, 90)
turtle.pendown()

# draw a very thin line
turtle.pensize(0.1)
turtle.forward(100)

# move back to the left side of the screen
# and a little further down
turtle.penup()
turtle.goto(-50, 50)
turtle.pendown()

# set the pen color to RED using RGB color values
turtle.pencolor(1.0, 0, 0)

# thicker line
turtle.pensize(2)
turtle.forward(100)

# move back to the left side of the screen
# and a little further down
turtle.penup()
turtle.goto(-50, 0)
turtle.pendown()

# set the pen color to BLUE using RGB color values
turtle.pencolor(0, 0, 1.0)

# thicker line
turtle.pensize(7)
turtle.forward(100)

# move back to the left side of the screen
# and a little further down
turtle.penup()
turtle.goto(-50, -50)
turtle.pendown()

# set the pen color to a custom color using RGB color values
turtle.pencolor(0.7, 0.5, 0.2)

# thicker line
turtle.pensize(20)
turtle.forward(100)```

#### Creating Random Colors

Recall that Python's `random` module contains functions that can be used to generate random integers or floating point values. For example, if you wanted to generate a random integer between 0 and 100 you could do the following:

`num1 = random.randint(0, 100)`

With a little division we could turn this number into a floating point number to express a percentage. For example, the variable 'num1' below will be a floating point number between 0.0 and 1.0 (inclusive):

`num1 = random.randint(0, 100) / 100`

Now we have all of the tools we need to pick random colors! We can ask Python to generate three random numbers and use them as arguments to the `pencolor` function - this will allow us to draw randomly colored lines to the screen. Here's an example - every time you run this program a different color will be generated!

```# make the turtle graphics module available
import turtle

# also make the random module available
import random

# set up our graphical canvas
# width = 500, height = 500
turtle.setup(500, 500)

# pick a random red value!
# start by choosing a random integer between 0 and 100
# then divide it by 100 - this will generate a float between 0.0 and 1.0
red = random.randint(0, 100) / 100

# do the same thing for green and blue
green = random.randint(0, 100) / 100
blue  = random.randint(0, 100) / 100

# use these numbers to set our pen color
turtle.pencolor(red, green, blue)

# draw a line
turtle.pensize(10)
turtle.forward(100)```

### Quiz

Now that you've completed this module, please visit our NYU Classes site and take the corresponding quiz for this module. These quizzes are worth 5% of your total grade and are a great way to test your Python skills! You may also use the following scratch space to test out any code you want.

### Feedback     