Loops

Loops are a very important part of Python, all languages as a whole.

  • If you generate an infinite loop use the CTRL+C to stop running the script

For Loop


for loops are covered in most languages, in Python the same applies as well.

# Measure some strings using a for loop
words = ['cat', 'window', 'defenestrate']
for w in words:
    print(w, len(w)) 
cat 3
window 6
defenestrate 12

Sequence

A for loop in programming is a control structure that allows the repeated execution of a set of statements for each item in a sequence, such as elements in a list or numbers in a range, enabling efficient iteration and automation of tasks. for loops are useful when we know exactly the number of iterations we require. If the number is unknown, use while loop

in

  • Use in to check the condition of the for loop
  • The for loop picks each x in the samplelist and execute the block of code in the loop
samplelist = [1,3,5,4,9,4,7,0]
for x in samplelist:
    print(x)
1
3
5
4
9
4
7
0

Range

All for loop conditions apply when using range EXCEPT:

When using a range the loop stops one short of the last value. What does that mean? It means it does NOT include the last number. Look at the example below:

  • Range could be misleading at first, one assumes that range(0,10) would cause the for loop to iterate from 0 up to an including 10
  • That would mean we will have 11 iterations
  • In other words, if we ask Python to iterate through a for loop with: for x in range(1,12) one would think the first iteration would be with x=1 and it will loop through until the final iteration when x=12
  • That’s not actually true because that will actually gives us 12 iterations and range(1,12) is 12-1=11
  • Here are some examples:
range(10)
range(0, 10)
# This would give us 10 iterations: 10-0=10 with the last iteration stopping at x = 9
  • range(10) or range(0,10) will count from 0 to 9
  • If you wanted to count from 1 to 10 then use range(1,11) which generates a sequence from 1 to 10
for x in range(10):
    print('x = ',x)
x =  0
x =  1
x =  2
x =  3
x =  4
x =  5
x =  6
x =  7
x =  8
x =  9
for x in range(1,12):
    print('x = ',x)
x =  1
x =  2
x =  3
x =  4
x =  5
x =  6
x =  7
x =  8
x =  9
x =  10
x =  11

What’s important is to note that even though the maximum value of the range is 12 the actual range is 12-1=11

  • So as you see, x will loop through 11 times
  • Here is another example
  • As you see we still get 11 cycles through the loop because 11-0=11
  • So pay attention to the range not the max value =y of the range provided in the range(x,y)
for x in range(0,11):
    print('x = ',x)
x =  0
x =  1
x =  2
x =  3
x =  4
x =  5
x =  6
x =  7
x =  8
x =  9
x =  10
  • Let’s try some more
for y in range(5, 10):
    print('y = ',y)
y =  5
y =  6
y =  7
y =  8
y =  9

Increments

  • We can actually use a range and increments simultaneously range( x, y, incr)
  • incr is the increment we want to add to x after every iteration
  • we stop when the increment added to the current value of the looping index is equal to or exceeds y
for z in range(0, 10, 3):
    print('z = ',z)
z =  0
z =  3
z =  6
z =  9
for w in range(-10, -100, -30):
    print('w = ',w)
w =  -10
w =  -40
w =  -70

Index

  • We can loop through the index of a string using a for loop
  • Let’s break it down:
    • if you remember indexing starts with the first object being [0], so a[0] = ‘Mary’ and a[4]= ‘lamb’

    • len(a) = 5

    • range(len(a)) = range(5) = range(0,5)

    • it means we will have 5-0= 5 iterations, starting with 0 and ending at 4

a = ['Mary', 'had', 'a', 'little', 'lamb']
for i in range(len(a)):
    print(i, a[i])
0 Mary
1 had
2 a
3 little
4 lamb

Enumerate

  • Have you ever needed to keep track of both the item and its position in a list?
  • An enumerated for loop is like having a personal assistant who not only hands you the item but also tells you where to find it.

Consider this example:

fruits = ["apple", "banana", "orange"]
for index, fruit in enumerate(fruits):
    print(f"At position {index}, I found a {fruit}")
At position 0, I found a apple
At position 1, I found a banana
At position 2, I found a orange

Here is another one:

a = ['Mary', 'had', 'a', 'little', 'lamb']
for x, i in enumerate(a):
        print(f"We are at position {x}, and the word is {i}")
We are at position 0, and the word is Mary
We are at position 1, and the word is had
We are at position 2, and the word is a
We are at position 3, and the word is little
We are at position 4, and the word is lamb

While Loop


If you haven’t used while before, think of while as an until loop. while loop will repeat itself while the condition is met. It’s like saying “keep dancing till the music stops”. while loops are useful when the number of iterations is unknown, and will continue till a condition is met

  • Syntax: while condition: \n execute code don’t forget the indentation
  • Note in the example below the loop will not stop till the counter reaches 11

Important: whatever counter you are using it needs to be incremented otherwise you’ll get stuck in an infinite loop

counter = 2
while counter <= 10:
        print(counter)
        counter += 1
2
3
4
5
6
7
8
9
10

Infinite Loop


If you ever catch yourself in an infinite loop, use CTRL+C to stop the script from running

Examples


for: -5 to 5

  • Write a for loop the prints out all the element between -5 and 5 using the range function.
for i in range(-4, 5):
    print(i)
-4
-3
-2
-1
0
1
2
3
4

in Sequence

  • Print elements of list
Genres = ['rock', 'R&B', 'Soundtrack', 'R&B', 'soul', 'pop']
for Genre in Genres:
    print(Genre)
rock
R&B
Soundtrack
R&B
soul
pop
  • Print two multiplication tables for 6 and 7
print("Multiplication table of 6:")
Multiplication table of 6:
for i in range (10):
    print("6*",i,"=",6*i)
6* 0 = 0
6* 1 = 6
6* 2 = 12
6* 3 = 18
6* 4 = 24
6* 5 = 30
6* 6 = 36
6* 7 = 42
6* 8 = 48
6* 9 = 54
print("Multiplication table of 7:")
Multiplication table of 7:
for i in range (10):
    print("7*",i,"=",7*i)
7* 0 = 0
7* 1 = 7
7* 2 = 14
7* 3 = 21
7* 4 = 28
7* 5 = 35
7* 6 = 42
7* 7 = 49
7* 8 = 56
7* 9 = 63

while sequence

  • Write a while loop to display the values of the Rating of an album playlist stored in the list PlayListRatings.
  • If the score is less than 6, exit the loop.
  • The list PlayListRatings is given by: PlayListRatings = [10, 9.5, 10, 8, 7.5, 5, 10, 10]
PlayListRatings = [10, 9.5, 10, 8, 7.5, 5, 10, 10]
i = 0
rating = PlayListRatings[0]
while(i < len(PlayListRatings) and rating >= 6):
    print(rating)
    i = i + 1 
    rating = PlayListRatings[i] 
10
9.5
10
8
7.5

while to copy

  • Write a while loop to copy the strings 'orange' of the list squares to the new list new_squares
  • Stop and exit the loop if the value on the list is not 'orange'
squares = ['orange', 'orange', 'purple', 'blue ', 'orange']
new_squares = []
i = 0
while(i < len(squares) and squares[i] == 'orange'):
    new_squares.append(squares[i])
    i = i + 1
print (new_squares)
['orange', 'orange']
  • Use while loop to search for animals made up of 7 letters
  • Extract those animals into a new list: New
Animals = ["lion", "giraffe", "gorilla", "parrots", "crocodile","deer", "swan"]
New = []
i=0
while i<len(Animals):
    j=Animals[i]
    if(len(j)==7):
        New.append(j)
    i=i+1
print(New)
['giraffe', 'gorilla', 'parrots']