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.

22 KiB

Python Programming: Loops


Learning Objectives

After this lesson, you will be able to:

  • Use a for loop to iterate a list.
  • Use range() to dynamically generate loops.
  • Use a while loop to control program flow.
  • Use break to exit a loop.

Discussion: A Small List

This situation isn't 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 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.


We Do: 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.


We Do: Write a Loop - Making 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 or person).
  • Inside your loop, add the code to print "Hello," plus the name.
"Hello, Felicia!"
"Hello, Srinivas!"

We Do: Write a loop to greet people on 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!"

Discussion: 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 6 times.

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

Or only want to loop some of it?

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:


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: 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.


We Do: 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?


We Do: 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

That's 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.
  • Runs until the user guesses.

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 put the above. Run it! What happens? Does it work?


You Do: A Guessing Game

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

Decide who will be driver and who will be 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?


You Do: 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?


Summary + Q&A

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 use indices, not duplicates, so it lets you modify the collection.

while loops:

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

That was a tough lesson! Any questions?


Additional Reading