Another Look at While Loops (It's the Sequel!)

What's a While Loop Again?

Describe what a while loop is…

What is the while loop syntax?

while condition:
	print("execute this block of code")

Great. So. Why Even?

Sales Commission Program

Starting Out with Python has a program that:

  1. asks for a salesperson's number of sales and their rate
  2. …and then calculates their sales commission.
#  get a salesperson's sales and commission rate.
sales = float(input('Enter the amount of sales: '))
rate = float(input('Enter the commission rate: '))

#  calculate the commission
commission = sales * rate

#  display the commission
print("the commission is $" + str(commission))

Commission for 10, Please?

Is it possible to change the code in the previous slide so that the program requests data and calculates commissions for 10 salespersons … WITHOUT USING A WHILE LOOP?

Of course! It's tedious, but just write the code 10 times!

sales = float(input('Enter the amount of sales: '))
rate = float(input('Enter the commission rate: '))
commission = sales * rate
print("the commission is $" + str(commission))

sales = float(input('Enter the amount of sales: '))
rate = float(input('Enter the commission rate: '))
commission = sales * rate
print("the commission is $" + str(commission))

#  and keep on going...

What About Counting?

Can you write a program to count from 1 to 5 by printing out each number on a new line WITHOUT USING A LOOP (we saw this previously)

n, delta = 1, 1
print(n)
n = n + delta
print(n)
n = n + delta
print(n)
n = n + delta
print(n)
n = n + delta
print(n)

Counting Without a While Loop

Last Example for Motivating Loops, I Swear

Game Over

Continue? (Yes/No)

WITHOUT USING A WHILE LOOP, is it possible to write a program that:

Continue? (Yes keeps on going)
> Yes
Continue? (Yes keeps on going)
> Yes
Continue? (Yes keeps on going)
> No

Continue? (Yes/No)

We could try using consecutive nested if statements, but we don't know how deep the nesting could go.

answer = input('Continue? (Yes keeps on going) \n')

if answer == 'Yes':
	answer = input('Continue? (Yes keeps on going) \n')

	if answer == 'Yes':
		answer = input('Continue? (Yes keeps on going) \n')

		if answer == 'Yes':
			answer = input('Continue? (Yes keeps on going) \n')

Functions!?

def ask():
    answer = input('Continue? (Yes keeps on going) \n')
    if answer != 'Yes':
        ask()

ask()

Loops Will Make All of Those Previous Programs Easier to Write!

Iteration and Loops

Some formal definitions:

Two Types of Loops

There are two broad categories of loops:

A while loop is a condition controlled loop.

While Loops

Condition Controlled Loops

While Loop Logic

A flow chart representing a while loop:

While Loop Flow

While Loop Logic Continued

What happens if the condition is True?

* one or more statements are executed * condition is tested again What happens if the condition is False? The flow goes to the statements after the while loop

Compared to an If Statement

The flow chart for an if statement looks pretty similar to a while loop. What do you think the difference would be from the diagram showing while loop logic?

If Statement Flow Chart

If Statement Flow

While Loop Syntax

A template:

while condition: # the book calls this the while clause
	statement
	statement

Some real code:

a = 100
while a > -1:
	print(a)

What does this output? →

100
100
100

Basic While Loop Examples

Trivial Cases, Again

What do these snippets of code print out?→

while True:
	print("I'm true!")
while False:
	print("I'm false!")
I'm true!
I'm true!
I'm true!
#  nothing printed here

Let's Step Through True

while True:
	print("I'm true!")
  1. condition is true
  2. print "I'm true!"
  3. go back to top
  4. condition is true
  5. print "I'm true!"
  6. go back to top
  7. you know the deal

Let's Step Through False

while False:
	print("I'm false!")
  1. condition is false

We never even get into the body of the loop!

Slightly More Complicated

What does this print out? →

keep_on_going = True
while keep_on_going:
	print("I'm going!)"
I'm going
I'm going
I'm going
.
.
I'm going

Slightly More Complicated Continued

Let's add one line. What does this print out? →

keep_on_going = True
while keep_on_going:
	print("I'm going!")
	keep_on_going = False
I'm going

Slightly More Complicated Continued Continued

Going through each iteration

keep_on_going = True
while keep_on_going:
	print("I'm going!")
	keep_on_going = False

Loop ends after one iteration.

What Happened There?

Affecting the Outcome of the Condition

To change the outcome of your conditional:

Some Practical While Loop Examples

Handling Input, Continue Again

First an easy one. Let's go back to the continue program that we discussed earlier:

Continue? (Yes keeps on going)
> Yes
Continue? (Yes keeps on going)
> Yes
Continue? (Yes keeps on going)
> No

Continue Program, Some Questions

Continue Program Implementation

answer = input('Continue? (Yes keeps on going) \n')

while answer == 'Yes':
	answer = input('Continue? (Yes keeps on going) \n')

Notice that, like an if statement, variables declared outside of the body of the while loop can be accessed (and even changed) within the body of the while loop.

Another Continue Program Implementation

answer = 'Yes'

while answer == 'Yes':
	answer = input('Continue? (Yes keeps on going) \n')

(note that not all programs can fit this pattern)

A More Flexible Continue

Let's modify the previous program slightly so that it accepts either yes or yeah.

Continue? (Yes or Yeah will keep going)
Yeah
Continue? (Yes or Yeah will keep going)
Yes
Continue? (Yes or Yeah will keep going)
Nope

Flexible Continue Program, Some Questions

Flexible Continue Program, Implementation

To implement this, modify the condition appropriately by adding or answer == 'Yeah'

answer = input('Continue? (Yes or Yeah will keep going) \n')
while answer == 'Yes' or answer == 'Yeah':
	answer = input('Continue? (Yes or Yeah will keep going) \n')

Designing How Your While Loop Works

So, I Heard You Want to Repeat Some Code…

If you have some code that requires repetition, what questions should you ask?

We've Seen These Before… Some More Examples

Odd Numbers Except 13

Write a program that… →

There are a few ways to do this! What are some general strategies for solving this problem?→

Possible Solutions for Odd Numbers Except 13

Increment by 2's

n = 1
while n <= 99:
    if n != 13:
        print(n)
    n = n + 2

Using modulo to determine odds

n = 1
while n <= 99:
    if n % 2 == 1 and n != 13:
        print(n)
    n = n + 1

Accumulating Values

Write a program that will: →

Give me a number to add
> 10
Current total is 10
Give me a number to add
> 15
Current total is 25
Give me a number to add
> 5
Current total is 30
Give me a number to add
> 

Potential Solution for Accumulating Values

total = 0
while True:
    n = int(input("Give me a number to add\n> "))
    total = total + n
    print("Current total is " + str(total))

Average of Input

Write a program that continually asks the user for numbers, and asks them if they'd like to keep going. In the end, it should output the average of all of the numbers entered→

I'll calculate the average for you!
Current total: 0
Numbers summed: 0
Please enter a number to add
> 10
Do you want to continue adding numbers (yes/no)?
> yes
Current total: 10
Numbers summed: 1
Please enter a number to add
> 12
Do you want to continue adding numbers (yes/no)?
> no
The average is 11.0

Some Hints, Please?

Let's try keeping track of multiple variables:

An Average Solution

total = 0
count = 0
answer = 'yes'
print("I'll calculate the average for you!")
while answer == 'yes':
        print("Current total: " + str(total))
        print("Numbers summed: " + str(count))
        total = total + int(input("Please enter a number to add\n> "))
        count = count + 1
        answer = input("Do you want to continue adding numbers (yes/no)?\n> ")
print("The average is "+ str(total / count))

Syntactic Sugar

Increment / Decrement

We've used the following syntax to increment or decrement a variable

n = 0
n = n + 1

n = 100
n = n - 1

Slightly tedious…

Increment / Decrement Continued

There's some syntactic sugar that makes doing this less verbose: use += or -=

n = 0
#  adds one to n and binds the resulting value to n
n +=  1

n = 100
#  subtracts one to n and binds the resulting value to n
n -= 1

More Syntactic Sugar

This works for other operators too. What does this code print out? →

n = 2
n *= 2
n *= 2
print(n)

n = 64
n /= 2
n /= 2
print(n)
8
16.0

What About Strings?

Also works with strings…. What does this code print out? →

s = "h"
s += "e"
s += "y"
s *= 3
print(s)
heyheyhey

Some More Exercises!

Powers of Two

Continually print out the next power of two, only if you say 'y'

1
next power?
> y
2
next power?
> y
4
next power?
> n

Squares

Continually ask for a number, print out the square, and ask to continue

number
> 5
25
continue?
> y
number
> 2
4
continue?
> n

Other Exercises

…And For Loops