35
loading...
This website collects cookies to deliver better user experience
foo
, bar
, and math examples are your kryptonite, keep reading. This series uses relatable examples.# repeat these steps for every person in the group
# say hi
# give your name and pronouns
# say what you like to do when you’re bored
# mention something you could talk about for hours
for
loop. This doesn’t mean you need to know the exact number of times to repeat the code. I know that sounds contradictory, but I promise it’s not. Knowing the exact number of times to repeat the code can mean that you used some code to explain how many times. We often use len()
and range()
to get the exact number of repetitions. We’ll go over how range()
works then jump into some examples.range()
gives a “sequence of numbers and is commonly used for looping a specific number of times in for loops.”range(startNum=0, stopNum, step=1)
startNum
is the beginning of your range. It’s not required. The default is 0
.stopNum
is the end of your range.stopNum
and you will get that many numbers, though it will not include the stopNum
. This is because computers start counting at 0 and not 1.startNum
and stopNum
and you’ll get numbers from startNum
to stopNum
, but not including stopNum
.step
is like counting by 2s (2, 4, 6, 8). If you give it 5
it will give you every 5th number.# get numbers up to, but not including 100
for i in range(0, 100, 20):
print(i)
for
line? These are just like the if
blocks. The tab before the line is how Python knows this line is a step that belongs to the loop. The next line(s) that are not tabbed in are not part of a loop and therefore will not be repeated. They will run after the loop is done because computers read code top to bottom.range()
is giving us our exact number of times to run the loop. The range starts at 0, ends at but doesn’t include 100, and counts by or steps over 20. In this case, we get 0, 20, 40, 60, and 80.i
. I find it easier to understand my code when I use a descriptive name. A name is great, but we still need to know what the elusive i
is. In a for
loop, i
is a variable that only gets used within the loop.for
line, then it can be used in the block of loop code. With each repetition/iteration of the loop, any uses of the variable in the loop block will change. If the first repetition, the iterator variable was 0
, then in the second repetition the iterator variable was 1
, and so on.num
or digit
instead of i
. Read the syntax to yourself, substituting one of these for the i
. Does it make a bit more sense now? Diving into some real-life examples should help explain this better.i
. Know that when you’re reading it, you can substitute what makes sense to you.for
loops should be used when we want to repeat code and we know how many times to repeat it.# assume we have a list or sink full of 37 dirty dishes called dirty_dishes_list
# for every dish on the counter, wash it
for dish in dirty_dishes_list:
add_soap()
scrub_dish()
rinse_dish()
dry_dish()
print(dish + "has been cleaned")
print("DishBot 3000 has added soap")
. We are also missing a dirty_dishes_list
. Once you learn about lists, come back to this example, make a dirty_dishes_list
, and try out the code.# recipe pseudocode
# put all ingredients in a bowl
# mix for two minutes
# heat stove and dump mixed ingredients in pot on stove
# mix for five minutes
# recipe loops
# put all ingredients in a bowl
for ingredient in ingredients_list:
print(ingredient, "measured")
print(ingredient, "added to bowl")
# mix for two minutes
bowl_mix_minutes = 2
for minute in range(bowl_mix_minutes):
print("mixed ingredients for 1 minute")
# heat stove and dump mixed ingredients in pot on stove
print("Stove is turned on")
print("Mixture has been added to the pot")
# mix for two more minutes
stove_mix_minutes = 5
for minute in range(stove_mix_minutes):
print("mixed ingredients over heat for 1 minute")
.upper()
method. This method takes a string and makes all of the characters uppercase. You now know enough things to write the magic behind .upper()
. Let’s pseudocode it first.# pseudocoding .upper()
# save a string into a variable
# for every character in the string
# if the character is lowercase
# make the character uppercase and print
# if the character is a space, print the space
# if none of that (meaning the character is already uppercase), print the character
char
because it’s short for “character”.for
and if
? We can mix and match our spoken language with the programming language. This helps us start to form an idea of what we should be coding.for
loops and if
blocks. If you use them together, you’ll use combine the tabs to show Python you intend for one to be a part of another. For example, if you have an if
block as part of your for loop, the if
line will have one tab to show it is part of the for
loop. Then, the lines that are part of the if
block have two tabs to show it is part of the if
block that is inside a for
loop.# coding .upper()
words = "I smelled a goat at the store because I'm a snowman!"
for char in words: # for every character in the string
if ord(char) >= 97 and ord(char) <= 122: # if the character is lowercase
new_char_code = ord(char) - 32 # get the uppercase character code
new_char = chr(new_char_code) # use new_char_code to get uppercase letter
print(new_char, end="") # print new_char with no space at end
elif char == " ": # if char is a space
print(" ", end='')
else: # if none of the above (probably: char already uppercase or not a letter)
print(char, end='')
# original lines
new_char_code = ord(char) - 32 # get the uppercase character code
new_char = chr(new_char_code) # use new_char_code to get uppercase letter
# possible replacement
new_char = chr(ord(char) - 32) # get uppercase character code then get letter
for
loops when we can discern exactly how many times we need to repeat the code.while
loop. This means no programmer knows the exact number of times to repeat the code.counter = 0
while something_true:
print(counter)
counter = counter + 1
while
loops should be used when we want to repeat code and we don’t know how many times to repeat it. Instead, we give a comparison(s) or logical operator(s) to make a condition.# first ask the cat how many times they’d like to be pet, but don’t tell the human
preferred_pets_num = int(input("How many times would you like to be pet"))
pet_attempts = 0 # start with 0
while preferred_pets_num > pet_attempts:
print("You have consent to pet again")
print("purrrr, that pet was accepted")
pet_attempts = pet_attempts + 1 # add 1 every time you pet
print("That was 1 too many times. I'm leaving now")
dog_wants_to_play = True # dog always wants to play
sunny_outside = bool(input("Sunny? True/False"))
rainy_outside = bool(input("Raining? True/False"))
warm_outside = bool(input("Warm outside? True/False"))
cold_outside = bool(input("Cold outside? True/False"))
dog_energy = 100 # starting with 100%
outside_spent_energy = 3 # % energy spent fetching one time
inside_spent_energy = 2 # % energy spent fetching one time
while dog_energy > 50: # gotta leave pup some energy
if sunny_outside and warm_outside:
go_outside() # sets outside to True
if outside:
throw_ball()
print("Go get it!")
print("Drop it")
dog_energy = dog_energy - outside_spent_energy
elif rainy_outside or cold_outside:
throw_ball() # throw carefully, you're inside
print("Go get it!")
dog_energy = dog_energy - inside_spent_energy
sunny_outside
”. =
the old dog’s energy minus energy spent”. Without this line, we’d have an infinite loop and our poor dog would be so tired they may get hurt.go_outside()
and throw_ball()
) for a line like: print("We are outside now.")
. You would also have to change if outside:
to if True:
.earth_exists = True
# while the earth_exists
# water falls back to earth - precipitate
# water collects
# water evaporates
# clouds form - condensation
your_choice = input("Heads or Tails?").lower()
coin_landed = "heads"
if coin_landed == your_choice:
print("You win")
else:
print("You lost")
rounds_won = 0 # start with 0
rounds_lost = 0 # start with 0
total_rounds = 0 # start with 0
while total_rounds < 3:
your_choice = input("Heads or Tails?").lower()
coin_landed = "heads" # you can change this
if coin_landed == your_choice:
print("You win this round")
rounds_won = rounds_won + 1
else:
print("You lost this round")
rounds_lost = rounds_lost + 1
total_rounds = total_rounds + 1
# calculate who won
if total_rounds == 3 and rounds_won >= 2:
print("You win! You got best 2 out of 3")
else:
print("You lose! Computer got best 2 out of 3")
input().lower()
we are acknowledging that a player may input something with different capitalization and we are making sure it will match out coin_landed
exactly.=
the old rounds won plus one” or “current rounds lost =
the old rounds lost plus one”.while
loops when we cannot know exactly how many times we need to repeat the code.jump()
or turn_wheel()
) to fill in the if-elif-else then blocks# coding a for loop
# coding a while loop
# pets are a mix of birds, fish, cats, dogs, and reptiles
for pet in the range of 1 to 10
feed_pet()
brush_pet()
give_water()
take_outside()
play()
while dog_awake:
if dog_energy is more than 50;
dog_awake = True
dog_energy = 100
chase_cat()
chew_toy()
beg_for_pets()
dog_energy = dog_energy - 5
else: # dog_energy low
nap_time() # changes dog_awake to False
print("It’s doggy nap time!")
# coding .lower()
# coding .title()
throw()
or move_left()
) to fill in the if-elif-else then blocks.# scoring for any game