You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

24 KiB

Python Programming


Loops


Discussion: A Small list

This situation isnt so bad…

  visible_colors = ["red", "orange", "yellow", "green", "blue", "violet"]
  print(visible_colors[0])
  print(visible_colors[1])
  print(visible_colors[2])
  print(visible_colors[3])
  print(visible_colors[4])
  print(visible_colors[5])

But, what would we do if there were 1,000 items in the list to print?


The "For" Loop


The for Loop

The for loop always follows this form:

for item in collection:
  # Do something with item

For example:

visible_colors = ["red", "orange", "yellow", "green", "blue", "violet"]
for each_color in visible_colors:  
  print(each_color)

Knowledge Check: What Will This Code Do?

Think about what the code will do before you actually run it.


Writing a Loop

Let's write a loop to print names of guests.

First, we need a list.

  • Create a local .py file named my_loop.py.
  • Make your list: Declare a variable my_list and assign it to a list containing the names of at least five people.

Write a Loop — Make the Loop

Now we'll add the loop.

  • Skip a line and write the first line of your for loop.
    • For the variable that holds each item, give it a name that reflects what the item is (e.g., name of person).
  • Inside your loop, add the code to print "Hello," plus the name.
"Hello, Felicia!"
"Hello, Srinivas!"

Write a Loop Greeting Your Guest List

Our guests are definitely VIPs! Let's give them a lavish two-line greeting.

  • Inside your loop, add the code to print another sentence of greeting:
"Hello, Srinivas!"
"Welcome to the party!"

Where Else Could We Use a Loop?

A loop prints everything in a collection of items.

  • guest_list = ["Fred", "Cho", "Brandi", "Yuna", "Nanda", "Denise"]

What, besides a list, could we use a loop on? Hint: There are six on this slide!


Looping Strings

Loops are collections of strings and numbers.

Strings are collections of characters!


What About… Looping for a Specific Number of Iterations?

We have:

guest_list = ["Fred", "Cho", "Brandi", "Yuna", "Nanda", "Denise"]
for guest in guest_list:  
  print("Hello, " + guest + "!")

The loop runs for every item in the list — the length of the collection. Here, it runs six times.

What if we don't know how long guest_list will be?

Or only want to loop some of it?


Range()


Enter: Range

range(x):

  • Automatically generated.
  • A list that contains only integers.
  • Starts at zero.
  • Stops before the number you input.

range(5) # => [0, 1, 2, 3, 4]


Looping Over a Range

Let's look at range() in action:


Looping Over a Range

Looping over names here is really just going through the loop four times: At index 0, 1, 2, and 3. We can instead use range() to track the index and loop names: range(4) is [0, 1, 2, 3]. We can then use len(names), which is 4, as our range.


Using range() to Modify Collections

Why would you use range() on a list, when you could just loop the list?

We can't do:

guest_list = ["Fred", "Cho", "Brandi", "Yuna", "Nanda", "Denise"]

for guest in guest_list:
    guest = "A new name"

But we can do:

guest_list = ["Fred", "Cho", "Brandi", "Yuna", "Nanda", "Denise"]


for guest in range(len(guest_list)):
    guest_list[guest] = "A new name"

Looping Over a Range

Lets make this list all uppercase:


Knowledge Check

my_list = ['mon', 'tue', 'wed', 'thu', 'fri']

Which of the following lines is correct?

for day in range(my_list): # answer A
for day in range(len(my_list)): # answer B
for day in range(my_list.length): # answer C

Solo Exercise: Range() (510 minutes)

Locally, create a new file called range_practice.py.

In it:

  • Create a list of colors.
  • Using a for loop, print out the list.
  • Using range(), set each item in the list to be the number of characters in the list.
  • For example:
["red", "green", "blue"]
# =>
[3, 5, 4]

Quick Review: for Loops and Range

for Loops

# On a list (a collection of strings)guest_list = ["Fred", "Cho", "Brandi", "Yuna", "Nanda", "Denise"]
for guest in guest_list:
  print("Hello, " + guest + "!")

# On a string (a collection of characters)
my_string = "Hello, world!"
for character in my_string:
  print(character)

##### Range #####
range(4)  # => [0, 1, 2, 3]

# Using Range as an Index Counter
names = ["Flint", "John Cho", "Billy Bones", "Nanda Yuna"]
for each_name in range(4):
  print(names[each_name])

Quick Review: for Loops and Range

# OR

for each_name in range(len(names)):
  print(names[each_name])

# Using Range to Change a List:

guest_list = ["Fred", "Cho", "Brandi", "Yuna", "Nanda", "Denise"]
for guest in range(len(guest_list)):
  guest_list[guest] = "A new name"

The “While” Loop


The while Loop

What about "While the bread isn't brown, keep cooking"? Python provides two loop types.

for:

  • You just learned!
  • Loops over collections a finite number of times.

while:

  • You're about to learn!
  • When your loop could run an indeterminate number of times.
  • Checks if something is True (the bread isn't brown yet) and runs until it's set to False (now the bread is brown, so stop).

while Loop Syntax

# While <something> is True:
#     Run some code.
#     If you're done, set the <something> to False.
#     Otherwise, repeat.

a = 0
while a < 10:
    print(a)
    a += 1

while Loop Syntax


while: Be Careful!

Don't ever do:

a = 0
while a < 10:
    print(a)

And don't ever do:

a = 0
while a < 10:
    print(a)
a += 1

Your program will run forever! If your program ever doesn't leave a loop, hit control-c (break).


Filling a Glass of Water

Create a new local file, practicing_while.py.

In it, we'll create:

  • A variable for our current glass content.
  • Another variable for the total capacity of the glass.

Let's start with this:

glass = 0
glass_capacity = 12

Can you start the while loop?


Filling a Glass of Water

Add the loop:

glass = 0
glass_capacity = 12

while glass < glass_capacity:
    glass += 1  # Here is where we add more water.

Thats it!


Side Note: input()

Let's do something more fun. With a partner, you will write a program that

  • Has a user guess a number.
  • But first, how do we have users input numbers? Using input().
user_name = input("Please enter your name:")
# user_name now has what the user typed.
print(user_name)

Erase the code in your practicing_while.py file and replace it with the above code. Run it! What happens? Does it work?


A Guessing Game (5 minutes)

Now, get with a partner! Let's write the game.

Decide who will be the driver and who will be the navigator. Add this to your existing file.

  • Set a variable, answer to "5" (yes, a string!).
  • Prompt the user for a guess and save it in a new variable, guess.
  • Create a while loop, ending when guess is equal to answer.
  • In the while loop, prompt the user for a new guess.
  • After the while loop, print: "You did it!"

Discuss with your partner: Why do we need to make an initial variable before the loop?


A Guessing Game (Solution)

answer = "4"
guess = input("Guess what number I'm thinking of (1-10): ")
while guess != answer:
    guess = input("Nope, try again: ")
print("You got it!")

How'd you do? Questions?


Conclusion


Python Programming: Loops

Lesson Summary

Today we explored:

  • Loops:

    • Common, powerful control structures that let us efficiently deal with repetitive tasks.
  • for loops:

    • Used to iterate a set number of times over a collection (e.g., list, string, or using range).
    • range() uses indices, not duplicates, so it lets you modify the collection.

Python Programming: Loops

Lesson Summary

Today we explored:

  • while loops:
    • Run until a condition is False.
    • Used when you don't know how many times you need to iterate.

Up Next: {Add Upcoming Lesson Topics/Pre-Work}


Q&A


Additional Resources


Additional Reading

Learn Python Programming: Loops Video

Python: For Loop

Python: Loops


Exit Tickets