For Loops

Let me introduce you to for loops. For loops are loops that allow us to repeat a procedure multiple times. For example it could allow us to go through all items in a list and perform an operation on each item. We could use a for loop to go through 200 images and collect responses for each image. Or we might want to add a measurement to a list for every iteration in the loop.

The most simple for loop creates a list of numbers.

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

In the loop above, the word for is the command that initiates the loop.

The i in the code, represents each item in the list and I can name it anything I want. I've just named it 'i' here because it's commonly used in programming.

The range(10) is a command, that loops 10 times and produces a number starting from 1 for each loop. i represents the output in each loop here, so if we print(i) and have a look at the output Shell, we get the numbers: 0 1 2 3 4 5 6 7 8 9.

##########Output###########
0
1
2
3
4
5
6
7
8
9

Notice that all the stuff we want to take place in a iteration of the loop has to be indented by one tabulator, so it goes from 0-9 instead of 1-10.

Another for loop goes through all the items in a list, and simply prints them out. In the example below you can see the code for creating this for loop.

new_list = ['curry', 'tacos', 'pasta', 'bolognese', 'rice', 'noodles']

for i in new_list:
    print(i)

##########Output:########## 
curry
tacos
pasta
bolognese
rice
noodles

If we want we can use the split() function that divides a string into segments by white space. So with a sentence, it would divide it up where there is a space between the words. And then we could turn it into a loop that prints out the newly split words in the list!

my_list = 'Hi there! How are you?'.split()

for i in my_list:
    print(i)

##########Output:########## 
Hi
there!
How
are
you?

We could also ask the loop to do two commands at once. For example we could ask it to print each word in the list and print the length of each word in the list:

for i in my_list:
    print(i)
    print(len(i))

##########Output:########## 
Hi
2
there!
6
How
3
are
3
you?
4

If, elif, else sentences combined with the for loop

There are lots of operations that can be done in loops. Even the if-else sentences can be put into them!
So let's try out the if, elif and else sentences with a loop. First I will give some random baby names a gender value and then create a list containing the names.

Marty = 'male'
Monica = 'female'
Stevie = 'male'
Myra = 'female'
Trevor = 'male'
Ronny = 'unknown'
babyList = [Marty, Monica, Stevie, Myra, Trevor, Ronny]

Now I will use the if, elif and else sentence and add some conditions.

for baby in babyList:
    if baby == 'male':
        print('blue gift')
    elif baby == 'female':
        print('purple gift')
    else:
        print('green gift')

##########Output:########## 
blue gift 
purple gift 
blue gift 
purple gift
blue gift
green gift

In the example above the loop goes through each name in the list and performs the correct commands. A blue gift is printed if the baby is a male, and a purple gift is printed if the baby is a female. Otherwise a green gift is printed if the baby's gender is still unknown/ neither male nor female.

Exercises

Exercise 1:

  1. Make a list containing the values [0, 0, 1, 2, 1, 0, 0, 0, 1]
  2. Make a loop that goes through the list and checks the values:
    • If the value is 0 it should print 'failure'.
    • If the value is 1 it should print 'better'.
    • If the value is any other value it should print 'good'.

Exercise 2:

I want to open a small fast food café.

  1. Make a list containing the different items I could sell. For example ['Hotdog', 'Burger', 'Chips', 'Fish', 'Cola', 'Fanta', 'Water', 'Coffee'].

I would like to assign a price to my items. Since I've never opened a business before I have no clue as to what the prices could be. Therefor I naively decided to use word length as an indicator of what the price should be.

  1. Make a loop that goes through the list and checks the word lengths. If the word is 6 letters long or higher, create a new variable called price and give it the value 36 kr.. (Hint: to ask python whether a word is equal to or higher than a value, use the phrase >= so: if len(i) >= 6:)
  2. If the word is 5 letters long give it price = 25 kr. Otherwise you an else statement and give the price of 15 kr. for all other lengths.
  3. I would like you to print out each word, it's length and it's price. Hint: use the % symbol to print it out nicer. Try it out::
    Print("Word: %s, Word Length: %s, Price: %s " % (i, len(i), price))

Summary of Code

#Here we tell Python to loop through 10 numbers. Python always starts from the number 0, so it loops through the numbers 0-9 and prints them out:
for i in range(10):
    print(i)

#Here we loop through the list we have made called new_list, and print out each value in the list as we loop through it:
for i in new_list:
    print(i)

#Here we loop through the list we made called my_list, print out each value in the list for each time it loops to the next item. This time we also print out the length of each word in the list as well:
for i in my_list:
    print(i)
    print(len(i))

#Here we loop through our list called babyList, and for each item in the list it loops through it prints out a different colour gift all depending on the item in the list's gender:
for baby in babyList:
    if baby == 'male':
        print('blue gift')
    elif baby == 'female':
        print('purple gift')
    else:
        print('green gift')

results matching ""

    No results matching ""