02. For and While loops break, continue, range()

If you're coming from another language (don't worry if you're not), you may have seen a for-loop like this:

for (int i = 0; i < N; i++) {
  // do something N times
}

Or perhaps a while-loop that looks like this:

while (x > 100) {
  // Keep running and decrement x, until done
}

For Python, instead of iterating until some condition is met, we iterate over a sequence of objects in a list or a string. We call such a data structure that we can iterate through an iterable, and a construct that moves through an iterable the iterator.

We'll look at how to loop through a given number of times with the range() function, but let's first look at how we can loop through lists.

Looping through a sequence

Sometimes we'll want to loop through a sequence (such as a string) and check for some condition. Let's say you want to count the number of vowels in a word.

def vowel_count(word):
  vowel_count = 0
  for c in word
    if c is in 'aeiou':
    vowel_count++
  else:
    print("Successfully looped through all words in paragraph.")
  return vowel_count

Loops may also contain an optional else statement, that executes at the termination of a loop. These clauses, however, won't run if the loop exits by a break or return statement.

In this case, the for statement is our iterator and our word is an iterator.

Looping through a list

Perhaps you want to check how many times a certain word appears in a paragraph. We can first break the paragraph into a list, each containing one word. Then we can loop through this list to see how many times our word matches.

def word_count(word, paragraph):
  word_count = 0
  words_in_paragraph = paragraph.split()
  for paragraph_word in words_in_paragraph:
  if word == paragraph_word:
    word_count++
  else:
    print("Successfully looped through all words in paragraph.")
  return word_count

We may just want to print out some items in a list, which we can do in just two lines.

petnames = ['zoey', 'freddy', 'princess']
for pet in petnames:
  print(pet)

The while loop

Besides the for-loop, we may use a while-loop, which runs until the expression is evaluated False. Each iteration proceeds, then goes back up top to check the original expression. If it's True, then the code block is repeated; if not, we break out.

while count < 5:
// Keep running until count becomes greater than 5
  count++
else: 
  // Run if loop ran through successfully (without a break)

Loop controlling: continue and break

In some cases you'll have reached a condition from within a loop that warrants a break or another iteration up from top.

break

The break keyword is used to exit the smallest containing loop. It completely stops the execution of the current code block and jumps out to the next line outside the for or while loop. This code block will continually repeat until the user types in STOP.

while True:
  print("I love you")
  if input is "STOP":
    break
  input = readline()

return

Another way to completely break out of a loop is the return statement, which is used from within a function. However, instead of going to the next line, return will take the handle to the position where the function was called. You may also return a variable with the return keyword.

continue

The continue keyword can be used to interrupt the current sequence, and loop back up to the top of the expression. This is to be used in for loops, when you want to move up to the next looping iteration without completing the code block. For example, let's say you want to count the number of multiples of m below some number n:

def count_multiples_below_n(m, n):
count = 0
for current_number in range(n):
    if m % current_number is 0:
        continue
    print(m + " is not a multiple of " + current_number)
    count++
return count

In the above example we used the range() function. Let's see what this does now!

range() function

To loop through a block of code a predetermined number of times or through a sequence of numbers, we use the range() function. Understanding how the range function and why we use it is an important to understand.

The nifty thing about the range() function is that it generates values as the loop operates. This means that no space is allocated on containing all the values. Let's think about this for a second through an example.

my_inefficient_range = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in my_inefficient_range:
  print(num)

This code seems perfectly normal, and runs flawlessly, but we are wasting a good amount of space storing a list of numbers that we are only using once. By using the range function, we can avoid using up this space, as the numbers will be generated for you as we go through the loop. Thus, on the first iteration, a value of 1 will be yielded to us.

for num in range(10):
  print(num)

Fun with ranges

We can see that the range() function doesn't print out properly since the values are not generated at once. To actually obtian a list, we have to wrap it around the list creator function.

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

Stepping in ranges

Note that the range function is not just limited to consecutative integers starting at 0. We can specify a start position, and even a (negative) step function.

>>> list(range(0, 30, 3))
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
>>> list(range(75, 5, -3))
[75, 72, 69, 66, 63, 60, 57, 54, 51, 48, 45, 42, 39, 36, 33, 30, 27, 24, 21, 18, 15, 12, 9, 6]

Aching back from coding all day?

Prism Glasses

Aching back from coding all day? Try Back Problems

Ever feel achy from sitting crunched up on your computer table? Try lying down with these optical glasses that allow you to work on your laptop while lying flat on your back. This is the perfect solution with those with limited mobility or those who wish to prevent neck cramps and back strains.

$ Check price
4.454.45Amazon 4 logo(128+ reviews)

More Back Problems resources

Learn to be a Pythonista!

Introducing Python

Learn to be a Pythonista! Try Python

Easy to understand and fun to read, Introducing Python is ideal for beginning programmers as well as those new to the language. Author Bill Lubanovic takes you from the basics to more involved and varied topics, mixing tutorials with cookbook-style code recipes to explain concepts in Python 3. End-of-chapter exercises help you practice what you learned.

$ Check price
39.9939.99Amazon 4.5 logo(37+ reviews)

More Python resources

Ad