Iterations

Updating Variables

You don't need to make a new variable name every time you want to update its value (this is part of why it is called a 'variable', because its contents are variable). It is common to update a single variable.

# BAD
count = 0
count1 = count + 1

# GOOD
count = 0
count = count + 1

In [ ]:
count = 5
count = count + 10
count = count - 3
print(count)

Actually it is even easier. There are special operators to add, subtract, multipy, and divide into the current variable.

+=
-=
*=
/=

In [ ]:
print(count)
count += 5
print(count)
count *= 2
print(count)

TRY IT

Assign 5 to the variable x and then in a new line add 2 to x and store the result back in x.


In [ ]:

While loops

Loops are one of the most powerful feature of programming. With a loop you can make a computer do some repetitive task over and over again (is it any wonder that computers are taking our jobs?)

The while loop repeats while a condition is true and stops when that condition is false

while (condition):
    code to run

Each time a while loop runs, the condition is checked, if the condition is true, the code inside the loop runs and then it goes back and checks the condition again.


In [1]:
feet_of_snow = 0
while (feet_of_snow < 3):
    print("Snow is falling!")
    feet_of_snow += 1
print("We got " + str(feet_of_snow) + " feet of snow :(")


Snow is falling!
Snow is falling!
Snow is falling!
We got 3 feet of snow :(

TRY IT

Write out a while loop that prints out the values 1 - 5


In [ ]:

Infinite loops

One thing you need to be careful of with while loops is the case where the condition never turns false. This means that the loop will keep going and going forever. You'll hear your computer's fan heat up and the program will hang. If you are doing any significant amount of programming, you will write an infinite loop, it cannot be helped. But watch out for them anyways.

HINT To stop an infinite loop in a jupyter notebook select Kernel->Restart from the menu above.


In [ ]:
snowflakes = 0
# This condition is never false so this will run forever 
while (snowflakes >= 0):
    snowflakes += 1
    
# If you ran this by accident, press the square (stop) button to kill the loop

In [ ]:
# The other common infinite loop is forgetting to update to a counting variable
count = 0
while (count < 3):
    print("Let it snow!")

TRY IT

Don't try it. Infinite loops aren't good code.


In [ ]:

Lists

A list is a sequence of values. These values can be anything: strings, numbers, booleans, even other lists.

To make a list you put the items separated by commas between brackets [ ]


In [ ]:
weathers = ['rain', 'sun', 'snow']
tens = [10, 10, 10, 10]
print(weathers)
print(tens)

You can access a single element in a list by indexing in using brackets. List indexing starts at 0 so to get the first element, you use 0, the second element is 1 and so on.

list[index]

In [ ]:
print(weathers[0])
print(weathers[2])

You can find the length of a list using the built-in function 'len'.

len(list)

In [ ]:
print(len(tens))

TRY IT

Create a list of famous storms and store it in a variable called storms.


In [ ]:

Break and Continue

There are other ways to control a loop besides its condition.

The keyword break immediately exits a loop. With break you can write a loop without a terminating condition that is not an 'infinite loop'.

Continue stops that iteration of the loop and goes back to the condition check.


In [ ]:
while True:
    user_message = eval(input('> '))
    # Leave when the user talks about snow.
    if user_message == 'snow':
        print("I don't want to hear about that.")
        break
    print("and then what happened?")

In [2]:
stock_up = ['eggs', 'milk', 'bread', 'puppies', 'cereal', 'toilet paper']
index = 0
while index < len(stock_up):
    item = stock_up[index]
    index += 1
    # Make sure we don't stock up on puppies
    if item == 'puppies':
        print("No! We are not getting another puppy.")
        continue
    print("Storm is coming, better stock up on " + item)


Storm is coming, better stock up on eggs
Storm is coming, better stock up on milk
Storm is coming, better stock up on bread
No! We are not getting another puppy.
Storm is coming, better stock up on cereal
Storm is coming, better stock up on toilet paper

For loops

For loops are a faster way of writing a common loop pattern. Many loops go through each element in a list. Python makes this easy.

for item in list:
    run code for item

In [ ]:
# Let's rewrite the stock up loop as a for loop (we'll add the puppies in later)
stock_up = ['eggs', 'milk', 'bread', 'puppies', 'cereal', 'toilet paper']
for item in stock_up:
    print("Storm is coming, better stock up on " + item)

See how much shorter it is? If you can use a for loop, then do use a for loop.

Also, since we don't have to increment a counter, there is less of a chance of an infinte loop.


In [ ]:
# Let's add the puppies condition just to show that break and continue work with for loops too
stock_up = ['eggs', 'milk', 'bread', 'puppies', 'cereal', 'toilet paper']
for item in stock_up:
    if item == 'puppies':
        print("No! We are not getting another puppy")
        continue
    print("Storm is coming, better stock up on " + item)

We can use loops to sum, average, or find the max or min

I'll give you some examples


In [4]:
hourly_snow_fall = [4, 3, 2, 4, 1, 4, 3, 2, 1, 1, 1, 0]

# Finding the sum
total_snow = 0
for hour in hourly_snow_fall:
    total_snow += hour
print("Total snow " + str(total_snow))


Total snow 26

In [5]:
# Finding the average
total_snow = 0
number_snowy_hours = 0
for hour in hourly_snow_fall:
    if hour == 0:
        # Ignore hours that it didn't snow
        continue
    total_snow += hour
    number_snowy_hours += 1  
ave_snow = total_snow / number_snowy_hours
print("Average snow " + str(ave_snow))


Average snow 2.3636363636363638

In [7]:
# Finding the max
max_snow = 0
for hour in hourly_snow_fall:
    if max_snow < hour:
        max_snow = hour
print("Max snow was " + str(max_snow))


Max snow was 4

TRY IT

Write a loop that find the maximum word length of a list of words (provided).


In [8]:
words = ['Oh', 'the', 'weather', 'outside', 'is', 'frightful', 'But', 'the', 'fire', 'is', 'so', 'delightful']

By the way, at this point you could go back to the previous lesson's project Yahtzee and use a loop to play until you get a yahtzee.

Range

Python has a built in function called range() that returns a generator of integers in order

 # If you only include 1 parameter it starts at zero and goes to that number-1
 range(5) #-> [0, 1, 2, 3, 4]
 # If you include 2 parameters it goes from [start, stop)
 range(2,5) #-> [2,3,4]
 # If you include 3 parameters it goes from [start, stop) and skips by the third number
 range(1,10,2) #-> [1,3,5,7,9]

What is a generator? Well it is a list that only stores one item at a time. We can just make it a list by using type casting list(generator). You can use generators without casting them to lists when you are in a loop.


In [ ]:
cumulative_snowfall = list(range(1, 15))
print(list(cumulative_snowfall))

You can use range as the iterable in a for loop instead of using a while loop with a counting variable if you just want to iterate over integers

for i in range(1,6):
    print(i)

In [9]:
for inches in range(1,7):
    suffix = " inch"
    if inches == 1:
        suffix += "."
    else:
        suffix += "es."
    print("It has snowed " + str(inches) + suffix)


It has snowed 1 inch.
It has snowed 2 inches.
It has snowed 3 inches.
It has snowed 4 inches.
It has snowed 5 inches.
It has snowed 6 inches.

TRY IT

Create a for loop that prints out the values 1 - 5 using range()


In [ ]:

Project: Wanderer

We are going to create a program that lets a user move N, S, E, or W and keeps track of their location. In phase two, we will introduce a treasure and let the user know if they found it.

Phase 1: wandering

  1. Initialize two variables wanderer_x and wanderer_y to 0.
  2. In an infinate while loop:
    • prompt the user "Which direction would you like to travel in? (N, S, E, or W. done to quit)" and store in a variable called direction
    • Update the user's location depending on their choice: add 1 to wanderer_x if E, subtract 1 from wanderer_x if W, add 1 to wanderer_y if N, subtract 1 from wanderer_y if S.
    • If their response is 'done' break out of the loop.
  3. Tell the user their location

Phase 2: treasure

  1. Initialize treasure_x and treasure_y to integers of your choice (don't make them too big or you'll have to spend too long to treasure hunt). Include this after you initialize the wanderer's location.
  2. In the while loop, after the user's location has been updated, if they are in the same location as the treasure, congratulate them and break out of the loop.

Phase 3: adventure!

Here are some ideas for how to improve your program.

  1. Make the location of the treasure random. ( x and y between -10 and 10)
  2. Set a time limit to find the treasure. Instead of an infinite loop, use a for loop from 0 - 50.
  3. Tell the user how far they walked d = sqrt( (x2 - x1)^2 + (y2 - y1)^2) Hint check the math module
  4. You should probably make #3 a function called distance that takes four parameters (x1, x2, y1, y2) and returns the distance.
  5. Now that you have your distance formula see if you can make your program say 'warmer' or 'colder' depending on if their distance is closer or further from the treasure than last time (remember to store the last time).
  6. You might want to add some error checking for if the user says something besides N, S, E, W, or done.

In [ ]: