Skip to content

Instantly share code, notes, and snippets.

@breadchris
Created May 27, 2022 15:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save breadchris/bc92f27ebfd41751592c7e01984d8a28 to your computer and use it in GitHub Desktop.
Save breadchris/bc92f27ebfd41751592c7e01984d8a28 to your computer and use it in GitHub Desktop.

All the ways to loop

Warmup

Follow the directions in the code. Use the Printing out a grocery list code as a template to write your for loop

Printing out a grocery list

  1. Copy this code into your project
  2. Add your own grocery item to the list
  3. Run the code to see if your grocery item gets printed out
# Printing your grocery list
groceries = ["apples", "carrots", "onions"]
for grocery in groceries:
  print("I need to get: " + grocery)

Adding numbers together

  1. Copy this code into your project
  2. Notice that this code will error when you run it because the variable sum_of_numbers doesn't exist
  3. Follow the instructions in the code to add this variable.
# Adding numbers together
numbers = [2, 6, 8]

# **Create** the variable sum_of_numbers and set it to 0

for number in numbers:
  sum_of_numbers += number

Counting to 10

  1. Copy this code into your project.
  2. Run the code see what it prints out.
  3. Change the code so that it doesn't just print out the numbers 0 through 9, but prints out 1 through 10
# Counting to 10
for counter in range(0, 10):
  print(str(counter))

Notice that "11" does not get printed out, even though 10 + 1 would equal 11. This means that counter never actually equals 10, even though in the range we say (0, 10)

Such a long word

  1. Copy this code into your project.
  2. Run this code and see what happens
for character in "supercalifragilisticexpialidocious":
  print(character)

Challenge: Reversing the alphabet

  1. Copy this code into your project.
  2. Edit the reverse function to loop over the variable string_to_reverse and reverse the characters.
def reverse(string_to_reverse):
  reversed_string = ""
  # your code goes here

reversed = reverse("abcdefghijklmnopqrstuvwxyz")
print(reversed)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment