Learning Objectives

  • Be able to repeatedly execute a block of code until a certain condition is met.
  • Be able to prematurely break a loop using the break keyword.
  • Understand what constitutes as an infinite loop.
  • Be able to prematurely execute the next iteration of a loop using the continue keyword.
  • Understand and be able to differentiate between the terms iterator and iteration.

Video


Loops

Loops give us the ability to repeatedly execute code until some condition is met. We have two types of loops that we commonly use in Python, (1) a for loop, and (2) a while loop.

Let’s say that we want to keep asking a user for their password until they get it right. This is an example of what a loop would be used for. For example, let’s take a look at a loop below waiting for the user to enter password.

CORRECT_PASSWORD = "john"
password = input("Enter password: ")
while password != CORRECT_PASSWORD:
   print("Invalid password.")
   password = input("Enter password: ")
print("Valid password")

Until the user enters the password “john”, they will be asked over and over again to enter a password. You can see that I had to provide the prompt twice (the input function), but we will see later how to remove this and make our code nice-n-slick!

This is an example of our first loop, the while loop.


While Loops

While loops execute a body of code as long as the condition holds true. It is much like an if statement, except that it keeps executing the code body as long as the condition is true. For example,

while 1 == 1:
   print("1 is 1")

The loop above is called an infinite loop since the condition will always hold true–and there is no way to stop this loop except for killing your program.

The while loop begins with the keyword, while, and then a condition follows. After the condition, we add a colon : to create a loop body. The while loop first checks the condition. If this condition is True, then the loop body is executed. After the loop body is executed, the condition is checked again. When the condition becomes False, the body is skipped and the code flow is resumed beyond the while loop.

We generally use while loops for some condition with an indefinite period–that is, the condition is NOT based on counting.


For Loops

For loops are great for counting. We use the range function with a for loop, or we look inside of a list with a for loop. The syntax starts with for:

my_list = [1, "John", 3, 4.7, 5, [6, 5, 4, 3], 7]
for item in my_list:
   print(item)

The code above will print the list, item by item, 1 through 7. The syntax for variable in values creates a variable, in our case item, to store each individual element.

For Ranges

We can use the range function to generate a set of values between two numbers. The range function can be used one of three ways:

  • range(end) – Generates numbers from 0 up to but not including end: [0..end)
  • range(start, end) – Generates numbers from start up to but not including end: [start..end).
  • range(start, end, step) – Generates numbers from start up to but not including end with the difference of step between each number.

If we want to run 10 iterations of a loop we can use:

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

The code above will print values 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. Notice that there are 10 total numbers, but since it starts with 0, it ends with 9.

We can also specify the start and ending points:

for i in range(10, 20):
   print(i)

The code above prints out 10, 11, 12, 13, 14, 15, 16, 17, 18, and 19. Again, this is 10 total numbers, but it excludes the end, which was 20.

Finally, the last form of the range function is to provide how far apart each number will be from each other. For example,

for i in range(10, 20, 3):
   print(i)

This code will print 10, 13, 16, and 19. Notice that the difference between each value is 3, which is the step we gave the range function.

Enumerating Index and Value

Sometimes you need both the position of a value as well as the value itself, we’ve seen we can do this using the index, but we can also use the enumerate function to give us a tuple with the position first followed by the value.

mylist = ["a", "b", "c", "d"]
for index,value in enumerate(mylist):
    print(f"{index} = {value}")

The code above produces the following:

0 = a
1 = b
2 = c
3 = d

The index,value part may look weird, but we can use this for index to take the first value in the tuple and value to take the second value in the tuple. This is called unpacking the tuple. We can rewrite above by capturing the tuple directly:

mylist = ["a", "b", "c", "d"]
for mytuple in enumerate(mylist):
    print(f"{mytuple[0]} = {mytuple[1]}")

The code above produces the same result, but I think it stylistically does not look as good as unpacking the values in Python.

By default, the enumerate function starts the index at 0, but sometimes, we don’t want to do that. Take for example the problem with the following code where I skip the first element in mylist.

mylist = ["a", "b", "c", "d"]
for index,value in enumerate(mylist[1:]):
    print(f"{index} = {value}")

The code above produces the following.

0 = b
1 = c
2 = d

The index of b is not 0, c is not 1, and d is not 2. This is because enumerate doesn’t know anything about the data type you are giving it. However, there is the start parameter we can use to tell Python the starting index.

mylist = ["a", "b", "c", "d"]
for index,value in enumerate(mylist[1:], start=1):
    print(f"{index} = {value}")

The code above, with start=1 produces the following output:

1 = b
2 = c
3 = d

Multiple Conditions

Sometimes checking to see if one condition is True or False is not enough. We can combine conditional statements using either the and or or keywords.

The and keyword

If we want all of the joined conditions to be True before executing a statement, we use the and keyword. The loop below will stop executing only if the username AND password are correct.


The or keyword

The or keyword requires that at least one condition is True. If at least one condition is True, then the entire condition becomes True.

CORRECT_USERNAME='john'
CORRECT_PASSWORD='password'

u = input("Enter username: ")
p = input("Enter password: ")
while u != CORRECT_USERNAME or p != CORRECT_PASSWORD:
   u = input("Enter username: ")
   p = input("Enter password: ")

We can sound out the condition above. Remember, as long as one condition is true when joined by an or, the entire statement is True, and the loop body will execute. So, “while u is not the correct username or p is not the correct password, then re-input u and p from the user.”

Indefinite Loops

We can modify the loop above to preclude us from having to write out the prompts twice by using an indefinite loop. An indefinite loop starts as an infinite loop, but a condition on the inside may execute a break statement, which will break the loop.

while True:
   u = input("Enter username: ")
   p = input("Enter password: ")
   if u == CORRECT_USERNAME and p == CORRECT_PASSWORD:
      break

The loop above now only has one set of prompts instead of two. Notice that it starts out as an infinite loop (while True). We use an if statement to check the validity of the inputs and break if they are correct. Notice that we do not have an else statement, so we will continually execute the loop until u is CORRECT_USERNAME and p is CORRECT_PASSWORD.