While Loops

Write a Program to Print out the numbers 1 through 5

Motivation for Loops

A program to count from 1 to 5

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)

Motivation for Loops Continued

Um. That was kind of tedious. Can't we just tell the computer to repeat those two lines of code?

YES! …using loops

n = 1
end = 5
delta = 1

while n <= end:
	print(n)
	n = n + delta

Iteration and Loops

Some formal definitions:

While Loops

Using a while loop allows us to:

While Loop Syntax

A template:

#  while <some sort of condition>:
# 	<do stuff here>

Some real code:

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

What does this output? →

100
100
100

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:

Figuring Out How to Write a While Loop

Before you write your while loop, you should probably first determine

Count From 2 Through 8 By 2's

How would you implement this?→

count = 2
while count <= 8:
	print(count)
	count = count + 2

Stepping Through Counting By 2's

count = 2
while count <= 8:
	print(count)
	count = count + 2
  1. count is 2
  2. condition is true because count (2) is less than 8
  3. print count
  4. add 2 to count… count is now 4
  5. condition is true because count(4) is less than 8..
  6. goes on until count gets to 10, at which point condition is no longer true

Check out the fancy step through

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

Do You Want Cake (Again)

Repeatedy ask if user wants cake until user says yes or yeah. How would you implement this?→

Do you want cake?
> no
Do you want cake?
> No
Do you want cake?
> yeah
Have some cake!
answer = 'no'
while answer != 'yes' and answer != 'yeah':
	answer = input("Do you want cake?\n> ")
print("Have some cake!")

Stepping Through Cake

Let's make an assumption that the user enters "no" first, and then "yeah" second.

answer = 'no'
while answer != 'yes' and answer != 'yeah':
	answer = input("Do you want cake?\n> ")
print("Have some cake!")
  1. answer is set to no by default
  2. condition is true, answer (no) is not 'yes' or 'yeah'
  3. answer is set to user input of 'no'
  4. condition is true, answer (no) is not 'yes' or 'yeah'
  5. answer is set to user input of 'yes'
  6. condition is false, answer != 'yeah' is now false!
  7. have some cake is printed

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))

A Difficult One…

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))

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

Other Exercises