Hour 7. Using Loops to Repeat Code


What You’ll Learn in This Hour:

Image How to repeat a block of code a set number of times

Image How to repeat code as long as something is true

Image When to use loops in the real world


A loop is a bit of code that is repeated. Sometimes it’s repeated a set number of times. Sometimes it’s repeated until a certain condition is true. Other times, it repeats until the user tells it to stop.

Most programs are written inside of loops. For example, a program on your computer continues to run until you decide to close it. A spell-checker tool in a text-editing program is a good example of a loop that only runs a certain number of times. It runs once for each mistake in the file, exiting the loop when the document is out of mistakes.

Repeating a Set Number of Times

Loops that are designed to run only a set number of times are called for loops. They may run for a certain number of times, or they may run once for every item in a list. A for loop has the following format:

for {VAR}  in {LIST}:
  code block
  code block
  code block

Each time the for loop runs, the variable in the VAR location will be set to the next item in the list. The block of code will be run, and then Python will go back to the top of the block. The next item in the list will be saved in VAR unless there’s nothing left. At that point, Python will skip the block and continue executing your code.

Getting a Range of Numbers

If you want a block of code to run a certain number of times, you’ll need to use range. The range built-in takes an integer and returns a list of numbers from zero to one less than the given integer. In this example, when we give range() the number “7,” Python gives us a list of numbers, starting with zero and ending with six. When we give range() a “3,” we get a list of numbers from zero to two.

>>> range(7)
[0, 1, 2, 3, 4, 5, 6]
>>> range(3)
[0, 1, 2]

If you don’t want to start at zero, give range() two numbers: your starting number and your ending number. Here, we give range() pairs of numbers. Each time, Python gives us a list of numbers starting at the first number and ending just shy of the second number.

>>> range(1,5)
[1, 2, 3, 4]
>>> range(20,25)
[20, 21, 22, 23, 24]
>>> range(-5, 5)
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]

You can even get range() to increment by a certain number (this is called a step). With step, you have to enter in all three variables: the beginning, end, and step. If you want only even numbers, for example, you can tell range() to start at two and go up by two with each step.

Here, we give range() a starting number (2), an ending number (20), and a number to step by (2). This gives us a list of even numbers from 2 to 18.

>>> range(2, 20, 2)
[2, 4, 6, 8, 10, 12, 14, 16, 18]

Getting a range is nice, but what we really want to do is combine a range of numbers with a for loop. There’s no need to save the range of numbers to their own variable. The loop will work just fine using range() on its own.

In this code snippet, we give range() a “5.” This would normally give us a list from zero to four. At the beginning of each loop, i is set to the next number in the range zero through four. We print out the value in i, then restart the loop, grabbing the next number in the list.

>>> for i in range(5):
...  print i
...
0
1
2
3
4

Naming Your Loop Variable

You don’t need to use i for your variable. Though this is one place where single-letter variables are often used, consider using a variable that makes sense for what your code is attempting to do. For example, if you’re looping through a number of years, you’d want to name the loop variable year.

Here, we want to loop over a list of years from 1980 to 2019. It makes more sense to call the loop variable year, rather than i, because it makes the code inside the loop easier to read.

>>> for year in range(1980, 2020):
...   print "In the {} ...".format(year)
...
In the 1980...
In the 1981...
In the 1982...
In the 1983...
In the 1984...
In the 1985...
In the 1986...
In the 1987...
In the 1988...
In the 1989...
(and so on...)

Iterating Through Lists

One of the great uses for loops is iterating through a list. It’s rare to see a program that doesn’t have a for loop that moves through a list, item by item. Here, we have a for loop that has been given a list of cats.

>>> cats = ['manx', 'tabby', 'calico']
>>> for cat in cats:
...   print "That's a nice {}  you have there!".format(cat)
...
That's a nice manx you have there!
That's a nice tabby you have there!
That's a nice calico you have there!

Each time the loop runs, cat is set to the next cat in the list, and a sentence is printed out, complimenting the cat.

Often, the variable that’s being set is a singular of whatever the list variable is called. This makes it easy for those reading your code later to see what your code is acting on. Variables such as i and index aren’t very descriptive and should be used sparingly.

Skipping to the Next List Item

Perhaps you want to move to the next item in the list before finishing the block of code beneath the for loop. Maybe you encountered some bad data, or maybe the code doesn’t apply in that one case. In this instance, use a continue statement.

Let’s say we want to divide 100 by a number in a list. If one of those numbers happens to be a zero, though, Python will give us an error. In this snippet, we test to see if the number is zero. If it is, we print an error message and then move on to the next item in the list.

>>> numbers = [5, 2, 0, 20, 30]
>>> for number in numbers:
...   if number == 0:
...       print "Ugh. You gave me a 0"
...       continue
...   new_number = 100.0/number
...   print "100/{}  = {} ".format(number, new_number)
...
100/5 = 20.0
100/2 = 50.0
Ugh. You gave me a 0
100/20 = 5.0
100/30 = 3.33333333333

Instead of going on to print the result of dividing 100 by zero, it moves to the next item in the list (in this case, 20).

Breaking Out of a Loop

If you come across an item in a loop and you want to stop the loop completely, this is where break comes in. break enables you to leave the loop and allows your program to begin executing the code after the loop block.

This can come in handy if we’re searching for a certain item in a list. Though a list has functions that allow you to see if it contains an exact item, there are times when you need a more nuanced approach. For example, you might want to see if any of the items in a user’s cart is over $100.

Here, we have the prices in a user’s cart saved into a list. This code snippet will iterate over the items in the cart. If it comes to an item that’s greater than $100, a warning message will be printed out.

>>> cart = [20.25, 30.04, 102.4, 50, 80]
>>> for item in cart:
...   print item
...   if item > 100:
...     print "You are going to require insurance on this order."
...     break
...
20.25
30.04
102.4
You are going to require insurance on this order.

The program stops running through the loop after hitting the item that costs $102.40. At that point, we’ve informed the user that the order will require insurance and skip the rest of the items in the list.

What if you don’t have to break out of a loop? You might want to print out something for users that won’t require insurance. Python has a statement for cases like this: else.

The else statement allows you to add another block of code to a for loop. This block is only run if you never break out of the for loop. In this example, we’re still looking for an item that’s worth more than $100.

>>> cart = [50.25, 20.98, 99.99, 1.24, .84, 60.03]
>>> for item in cart:
...   print item
...   if item > 100:
...     print "You are going to require insurance on this order."
...     break
... else:
...   print "No insurance will be required for this order."
...
50.25
20.98
99.99
1.24
0.84
60.03
No insurance will be required for this order.

There’s no item that’s over $100 (though one does come close), so all of the items in the list go through the for loop. Because a break is never used, the text in the else block is printed out.


Note: Loop Variable

The variable created by the for loop doesn’t go away after the for loop is done. It will contain the last value used in the for loop. So, if you’re looping over a list of dog breeds with a loop variable of dog, dog will contain the last item in the list once the loop is done.


Repeating Only When True

What if you don’t need to repeat code a set number of times, but rather only as long as a certain condition is met? This is where a while loop comes in. A while loop will run only as long as something is true. As soon as it isn’t true, the loop will stop running, and the program will continue.

While Loops

while loops are extremely useful when trying to get clean input from a user. Instead of crashing the program with bad input or exiting through a try/escape statement, you can keep trying until the user gets the input correct.

In this example, the user gives us an age. If the age he gives us isn’t made completely of numbers, Python prints an error statement and tries to get the user’s age again.

age = raw_input("Please give me your age in years (eg. 30): ")
while not age.isdigit():
  print "I'm sorry, but {}  isn't valid.".format(age)
  age = raw_input("Please give me your age in years (eg. 30): ")
print "Thanks! Your age is set to {} ".format(age)

The block beneath the while loop will continue to run until the statement not age.isdigit() is false. In order for that statement to be true, age.isdigit() needs to be true. In other words, the loop will keep running until the user enters something that’s all numbers. Here is some sample output:

Please give me your age in years (eg. 30): 24 years
I'm sorry, but 24 years isn't valid.
Please give me your age in years (eg. 30): twenty-four
I'm sorry, but twenty-four isn't valid.
Please give me your age in years (eg. 30): 24
Thanks! Your age is set to 24

Infinite Loops

So far, the code we’ve worked with has exited as soon as we’ve gotten the data we need, but that’s not how we usually want programs to work. We use programs to do a bunch of functions and then exit them when we’re done. If you won a game, you’d be surprised if the game shut down as soon as the end credits rolled. In general, the game asks if you want to quit before it exits. Maybe you want to start the game over or look at your achievements first.

One of the easiest ways to have a program exit only after the user is clearly done is to make an infinite loop. This is a loop that will keep going until you explicitly tell it to stop. Many times, this is called the program loop. Here, we have a loop that is set to run until the user enters q.

>>> while True:
...   text = raw_input("Give me some text, and I'll count the e's.
      Enter 'q' to quit: ")
...   if text == 'q':
...     break
...   print text.count('e')
...
Give me some text, and I'll count the e's. Enter 'q' to quit: Katie
1
Give me some text, and I'll count the e's. Enter 'q' to quit: Hannah
0
Give me some text, and I'll count the e's. Enter 'q' to quit: elderberries
4
Give me some text, and I'll count the e's. Enter 'q' to quit: q

A while loop doesn’t require an expression such as text == 'q' to run. while True is perfectly valid. True will always be true, so the loop won’t exit until you explicitly tell it to. You just have to be careful to make sure to add that break in somewhere, or your user might be stuck with a program that will never exit.

Using Loops in the Real World

Let’s go back to our restaurant example and the chef’s daily specials. In Hour 5, “Processing Input and Output,” she had a program that looked like this:

breakfast_special = "Texas Omelet"
breakfast_notes = "Contains brisket, horseradish cheddar"
lunch_special = "Greek patty melt"
lunch_notes = "Like the regular one, but with tzatziki sauce"
dinner_special = "Buffalo steak"
dinner_notes = "Top loin with hot sauce and blue cheese. NOT BUFFALO MEAT."

meal_time = raw_input('Which mealtime do you want? [breakfast, lunch, dinner] ')

print 'Specials for {} :'.format(meal_time)
if meal_time == 'breakfast':
  print breakfast_special
  print breakfast_notes
elif meal_time == 'lunch':
  print lunch_special
  print lunch_notes
elif meal_time == 'dinner':
  print dinner_special
  print dinner_notes
else:
  print 'Sorry, {}  isn 't valid.'.format(meal_time)

Each time the server wanted to get the specials, he had to run the script again, which is annoying. What if he could keep getting specials until he chose to quit? We can do that by adding a simple loop:

breakfast_special = "Texas Omelet"
breakfast_notes = "Contains brisket, horseradish cheddar"
lunch_special = "Greek patty melt"
lunch_notes = "Like the regular one, but with tzatziki sauce"
dinner_special = "Buffalo steak"
dinner_notes = "Top loin with hot sauce and blue cheese. NOT BUFFALO MEAT."

while True:
  meal_time = raw_input('Which mealtime do you want? [breakfast, lunch, dinner,
  q to quit] ')

  if meal_time == 'q':
    break

  print 'Specials for {} :'.format(meal_time)
  if meal_time == 'breakfast':
    print breakfast_special
    print breakfast_notes
  elif meal_time == 'lunch':
    print lunch_special
    print lunch_notes
  elif meal_time == 'dinner':
    print dinner_special
    print dinner_notes
  else:
    print 'Sorry, {}  isn 't valid.'.format(meal_time)

print "Goodbye!"

Rather than quit, the program will keep prompting the user to enter in a new mealtime. It won’t quit until the user enters q.

Now, when the program is run, we see this:

Which mealtime do you want? [breakfast, lunch, dinner, q to quit] breakfast
Specials for breakfast:
Texas Omelet
Contains brisket, horseradish cheddar
Which mealtime do you want? [breakfast, lunch, dinner, q to quit] lunch
Specials for lunch:
Greek patty melt
Like the regular one, but with tzatziki sauce
Which mealtime do you want? [breakfast, lunch, dinner, q to quit] q
Goodbye!

Summary

During this hour, you learned how to use a for loop to repeat a block of code a set number of times. You also learned how to use a for loop with a list to iterate over all the items in a list. Finally, you learned how to use a while loop to repeat a block of code until a statement is true.

Q&A

Q. What if I want a range that’s printed in descending order?

A. The format for a descending range looks a little different, but once you understand what’s going on, it makes sense. You start with the highest number, end with a number that’s one less from where you want to stop, and give a step of -1. Here’s how you would get a range from ten to one:

>>> range(10, 0, -1)
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

Q. What happens if I change a list while I’m looping through it?

A. This is an interesting question, and the answer changes for each programming language. In Python, if you change a list while looping through it, the loop will work with the change you made. This is generally easier to show than to explain. In this snippet, we have a list of fruit. If the given fruit is a banana, we want to add a pear to the list.

>>> fruit = ['apple', 'banana', 'mango']
>>> for item in fruit:
...   print 'Currently on: ', item
...   if item == 'banana':
...      fruit.append('pear')
...
Currently on:  apple
Currently on:  banana
Currently on:  mango
Currently on:  pear
>>> print fruit
['apple', 'banana', 'mango', 'pear']

Even though the list didn’t start off with “pear” when we began the for loop, when we added “pear,” it processed the new item. This can introduce some unexpected behavior, such as infinite loops or a list that doesn’t contain the items you’d expect based on what was printed. It’s probably best to stay away from doing this unless you’re certain about your logic.

Workshop

The Workshop contains quiz questions and exercises to help you solidify your understanding of the material covered. Try to answer all questions before looking at the answers that follow.

Quiz

1. What is the difference between a for loop and a while loop?

2. How would you get a range of even numbers, from 1 to 100?

3. How do you exit a loop?

Answers

1. A for loop runs through a list of items. A while loop will run until an expression is true.

2. You would need to use the range function. It would look like this:

range(2, 101, 2)

Note that we had to start at 2, not 1. If we started at 1, we would have gotten all of the odd numbers between 1 and 100.

3. For both for and while loops, the break statement is used to exit loops before they would exit on their own.

Exercise

Now that you can iterate through a list, rewrite the receipt script from the previous hour to be a bit easier to use. The waiter should be able to input a value for each seat, and the script should print out the total for all of the seats. The output should look like this:

Welcome to the receipt program!
Enter the value for the seat ['q' to quit]: 12
Enter the value for the seat ['q' to quit]: 15.50
Enter the value for the seat ['q' to quit]: 9.98
Enter the value for the seat ['q' to quit]: 14.05
Enter the value for the seat ['q' to quit]: q
*****
Total: $51.53

Keep in mind that you’re going to be getting both numbers and non-number values from the user. If an input isn’t valid, you should get a new value from the user.

Welcome to the receipt program!
Enter the value for the seat ['q' to quit]: five
I'm sorry, but 'five' isn't valid. Please try again.
Enter the value for the seat ['q' to quit]:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.148.210