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)
In [ ]:
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 :(")
In [ ]:
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!")
In [ ]:
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))
In [ ]:
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)
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))
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))
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))
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.
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)
In [ ]:
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.
wanderer_x
and wanderer_y
to 0.direction
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.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.Here are some ideas for how to improve your program.
distance
that takes four parameters (x1
, x2
, y1
, y2
) and returns the distance.
In [ ]: