Loops

Loops are statements used in python to repeat things iteratively. Iterating just means to do something one after another, For example counting from one to 10 requires you to count the current number and then move on the the next iteration until you reach 10.

In practice this means that loops are used to execute code multiple times until a certain condition is met. For example you could loop through the numbers 1-10 and print them out one after another.

All loops are composed of the loop type (while, for etc.) followed by the terminating condition (when the loop should end) and the loop body (what the loop should do on each iteration.)

while

A while loop is exactly as it sounds, it loops will continue until the condition is False. The basic syntax for a while loop looks like this:

while condition:
    # Do stuff at this indentation level while condition is True 
# Stuff at this indentation will run after the loop finishes

So for example, if you wanted to count from 0-10 and print every number on each loop the code would look like this:

x = 0 # Setup a variable to use for the conditional

while x <= 10: # Continue looping until x is greater than 10
    print(x) # Print the current itterations value of x
    x += 1 # Inrement x by 1 (add 1 to the current value of x)

print("loop Finished") # This will execute after the loop since it's at a lower indentation level

For

For loops are a bit more complicated than while loops. They loop based on iterables, which are things in python that you can iterate over. Collections such as lists, and tuples (and even strings) are examples of iterables. The terminating condition during for loops is when you hit the end of the iterable (i.e. the last element in a list).

The basic syntax of a for loop looks like this:

for variable in iterable:
    # Code at this indentation executes during the iteration
# Code at this indentation does stuff after the loop

Where variable is an arbitrarily named variable used to hold the current value of the iteration, and iterable is the item to iterate over.

Let's take the example of a shopping list and say you wanted to loop through the values in the list and print them off one by one, you could use a for loop to do this:

shopping_list = ["Eggs", "Ham", "Milk"]

for item in shopping_list: # Iterate through the shopping list
    print(item) # Print the item at the current iteration

This would print:

>> Eggs
>> Ham
>> Milk

break

The break statement is used to end a loop immediately. It can (but does not have to) be used with if/elif/else statements to force a loop to stop iterating if a condition is met.

Let's take the example that we want to create a for loop that print's out each letter of a string, but if the string contains a hyphen (-) then we want the loop to end. The code would look like this:

greeting = "Hello-World" # Setting up a string to iterate through

for character in greeting: # Iterate over the string one letter at a time
    if "-" in character: # if the current character is a hyphen
        print("Hyphen detected, ending loop!")
        break # End the loop
    else:
        print(character) # Print the current character

continue

Continue statements are used to jump to the next iteration. So for example let's say you wanted to print the even numbers from 0-10 using a while loop, you could do it like this:

x = 0 # Initialize a variable to use in the condition

while x < 10:
    if ((x % 2) == 0): # If the number is even
        print(x)

    else: # If the number is odd
        continue # Go to next iteration

Loop Tricks and Techniques

Here are some additionally useful things you can do with loops, as well as things to avoid.

Infinite Loops

When you are making a while loop, inevitably you will create a loop that never ends. Some languages stop you from doing this, python is not one of them. If you create a loop that wont stop, you can force the program to stop running by pressing ctrl+c on windows or cmd+c on mac.

Loop Nesting

You can execute loops inside of loops, this is useful in many cases. A good real world example is that some people will put lists inside lists, or dictionaries inside dictionaries. Here is an example of going through a list of shopping lists:

shopping_lists = [["Eggs", "Milk", "Ham"], 
                  ["Vinegar", "Mustard", "Ketchup"], 
                  ["Burgers", "Lettuce", "Mayo"]]

for current_list in shopping_lists: # Steps through the list of lists
    for item in current_list: # Steps through each list
        print(item) # Prints the item in the current shopping list

This prints:

Eggs
Milk
Ham
Vinegar
Mustard
Ketchup
Burgers
Lettuce
Mayo

Using loops for Validation

You can use a loop to validate input from a user. For example let's say you needed the user to input a number between 1-10, you could force them to do this in a loop like this:

while True: # This is an infinite loop
  number = int(input("Please type a number between 1 and 10: ")) # Take user input

  if number < 1: # Number is too small
    print("Number provided is less than 1")

  if number > 10: # Number is too large
    print("Number provided is greater than 10")

  else: # If the input is in a valid range
    break # End the loop

There is another way to do this syntactically (which I prefer):

valid_input = False # Used to mark if input is valid

while not valid_input: # Loop when valid input is False
  number = int(input("Please type a number between 1 and 10: ")) # Take user input

  if number < 1: # Number is too small
    print("Number provided is less than 1")

  if number > 10: # Number is too large
    print("Number provided is greater than 10")

  else: # If the input is in a valid range
    valid_input = True # End the loop

The only reason I perfer the way above is because if you forget to comment your code the above example is easier to read.

for loops over a set range

It is possible to create for loops that will loop for a specific range of numbers (i.e. 2-8). Let's take the example of looping from 5-10:

for number in range(5,11):
    print(number)

The range() function takes two arguments: The first is the number to start at, and the second is the number to end on. Also keep in mind the end number needs to be 1 more than the value you want to end on (most people use this for lists so this ensures that you don't go past the range of the list).

You can also opt to just specify an end number and the loop will start by default at 0. For example 0-10 would be:

for number in range(11):
    print(number)

Exercises

""" =========== Exercise 1 ============= Take the current for loop below and add two conditions to the loop body: 1. If 'Eggs' are the current element, then conitnue 2. If 'Sausages' is the current element, stop iterating. """ shopping_list = ["Bread", "Bannanas", "Pineapples", "Eggs", "Oranges", "Milk", "Sausages"] for item in shopping_list: # Iterate over the items in the shopping list # Do stuff None # Remove this and replace with your own loop body logic """ =========== Exercise 2 ============= Take the current existing shopping list and ask the user to add a number of items to the list. For example, if someone enters 3 then prompt them for input and append it to the list 3 times. """ amount_to_add = int(input("How many items do you want to add?")) counter = 0 # A counter to keep track of the number of items that have been added while counter <= amount_to_add: # Do stuff None # Remove this and replace with your own loop body logic

Challenges

""" =========== Challenge 1 ============= The code below generates a random number make a game that loops and takes user input at the command line. The input is the user's guess at what the number is. Taking their input you should print either: 'too high', 'too low' or 'Correct guess'. For example let's assume the number is 4 a sample output of the game would look like this: >> Enter Guess: 2 Too Low >> Enter Guess: 5 Too High >> Enter Guess: 4 Correct Guess """ import random number = random.randint(0, 10) # Generates a random number """ =========== Challenge 2 ============= Take two inputs from the command line, then convert both to an int the first number will be the starting number, and the second will be the ending number. Create a loop that goes from the starting number to the ending number, and only prints the even numbers. """ """ =========== Challenge 3 ============= THIS CHALLENGE IS HARD, DON'T GET DISCOURADGED IF YOU CAN'T DO IT! Using the list below print the numbers in ascending order. It should look like this: 1 2 3 4 5 6 7 8 9 HINTS: 1. The pattern is that the list is in order where the same index on each list is in ascending order. i.e. numbers[0][0] is 1 numbers[1][0] is 2 numbers[2][0] is 3 etc. 2. The simplest (and shortest) way to do this is with a loop counter variable, and a while loop. """ numbers = [ [1, 4, 7], [2 ,5, 8], [3, 6, 9] ]

Solutions




""" =========== Exercise 1 ============= Take the current for loop below and add two conditions to the loop body: 1. If 'Eggs' are the current element, then conitnue 2. If 'Sausages' is the current element, stop iterating. """ shopping_list = ["Bread", "Bannanas", "Pineapples", "Eggs", "Oranges", "Milk", "Sausages"] for item in shopping_list: # Iterate over the items in the shopping list if "Eggs" in item: continue elif "Sausages" in item: break else: print(item) """ =========== Exercise 2 ============= Take the current existing shopping list and ask the user to add a number of items to the list. For example, if someone enters 3 then prompt them for input and append it to the list 3 times. """ amount_to_add = int(input("How many items do you want to add?")) counter = 0 # A counter to keep track of the number of items that have been added while counter < amount_to_add: item = (input("What item would you like to add?: ")) shopping_list.append(item) counter += 1 print(shopping_list) """ =========== Challenge 1 ============= The code below generates a random number make a game that loops and takes user input at the command line. The input is the user's guess at what the number is. Taking their input you should print either: 'too high', 'too low' or 'Correct guess'. For example let's assume the number is 4 a sample output of the game would look like this: >> Enter Guess: 2 Too Low >> Enter Guess: 5 Too High >> Enter Guess: 4 Correct Guess """ import random number = random.randint(0, 10) # Generates a random number correct_guess = False while not correct_guess: guess = int(input("What is your guess?: ")) if guess < number: print("Too Low") elif guess > number: print("Too High") elif guess == number: print("Correct Guess") correct_guess = True """ =========== Challenge 2 ============= Take two inputs from the command line, then convert both to an int the first number will be the starting number, and the second will be the ending number. Create a loop that goes from the starting number to the ending number, and only prints the even numbers. """ start = int(input("Starting number: ")) end = int(input("Ending number: ")) x = start # Initialize x to the starting value while x <= end: if x % 2 == 0: # If the current x value is even print(x) x += 1 # Increment x by 1 else: x += 1 # Increment x by 1 """ =========== Challenge 3 ============= THIS CHALLENGE IS HARD, DON'T GET DISCOURADGED IF YOU CAN'T DO IT! Using the list below print the numbers in ascending order. It should look like this: 1 2 3 4 5 6 7 8 9 HINT: The simplest (and shortest) way to do this is with a loop counter variable, and a while loop. """ # This one is pretty hard, in the video for this lesson I explain it in depth. numbers = [ [1,4,7], [2,5,8], [3,6,9] ] x = 0 # Used to count how many itterations to do while x < 3: # Loop while x is less than the number of sublists in numbers print(numbers[0][x]) # Take the first lists x'th term and print it print(numbers[1][x]) # Take the Second lists x'th term and print it print(numbers[2][x]) # Take the Third lists x'th term and print it x += 1 # Increment loop counter by 1