6. Loops#

In some cases, we may want to run a block of code (set of statements) several times or to perform an operation on each item in a sequence. A loop statement allows us to do that efficiently. We have two commonly used loop statements:

  • For loop

  • While loop

6.1. For loop:#

For loops are used to iterate over a sequence; this can be a list or any other data structure in Python like a tuple, a dictionary, or a set. Below you can see the correct syntax for a for loop, where we multiply each item of the list by 10 and print it.

grade_list=[6, 5.5, 8, 4, 9.5, 9]

# multiply each item in the list by 10 and print it
for grade in grade_list:
  grade = grade * 10
  print(grade)

print(grade_list)
60
55.0
80
40
95.0
90
[6, 5.5, 8, 4, 9.5, 9]

Note:

  1. The grade is a variable that will be iteratively replaced with the items in the list. It is just a temporary variable, so the name you give it does not matter.

  2. You have to use : after the for statement.

  3. By using indentation we highlight a block of code. All statements with the same distance to the left belong to the for loop. Note that the second print command is out of the for loop and is only executed once.

  4. We performed the changes on the grade variable and didn’t apply them to the grade_list. That’s why the list remains unchanged at the end.

Here is another example program, which finds the average of the numbers in a list:

grade_list=[6, 5.5, 8, 4, 9.5, 9]

total=0 # to store the summation of all grades

for grade in grade_list:
  total += grade # total= total+ grade

print("Total: ", total)

average = total/len(grade_list)
print("Average: ", average)
Total:  42.0
Average:  7.0

Lastly, here is a practical example of a sorting algorithm which makes use of for loops. This sorting algorithm is called the Bubble Sort.

grade_list=[6, 5.5, 8, 4, 9.5, 9]
# Sort the numbers from smallest to largest
for i in range(len(grade_list)):
    for j in range(len(grade_list) - 1):
        if grade_list[j] > grade_list[j+1]:
            grade_list[j], grade_list[j+1] = grade_list[j+1], grade_list[j]
print(grade_list)
[4, 5.5, 6, 8, 9, 9.5]

6.1.1. Exercise: Finding the number of items (Optional)#

Create a Python program that receives a list of items as input and calculates the number of items within the list.

# Input: List of items (you can edit, extend, or shorten this list as you please):
input_list = ['apple', 4121, 231.42, 'kiwi', 32.4, 1, 1, 1, 1, 1]
# Calculate the amount of items:

# define a counter variable and set it to zer0
total_items = # your code here

# loop through the items in the list
for # your code here:
    # your code here # add one to the counter in each iteration

# Print the result
print(f"The number of items in the given list is: {total_items}")
  Cell In[5], line 4
    total_items = # your code here
                  ^
SyntaxError: invalid syntax

6.1.2. Exercise: Finding the average#

Create a Python program that receives a list of numbers as input and calculates the average of those numbers.

In the first block, create a program for calculating the sum of the numbers in a given list and print this sum.

Then, in the second block, calculate the average of these numbers and print its value.

# Input: List of numbers
input_numbers = [12, 24, 36, 48, 60]

# define a variable to save the sum, set it to zero in the begining
total_sum = 0

# loop through all the items in the list and add it to the total sum
for # your code here:
    # your code here

# Print the result
print("The sum of the given numbers is:", total_sum)
# Calculate the average of the sum of numbers:
# that is = total sum divided by the number of items in the list , use "len()""
average = # your code here

# Print the result
print("The average of the given numbers is:", average)

6.1.3. Exercise: Duplicate element remover#

Create a program that takes a list of numbers as input and removes duplicate elements, leaving only the unique ones.

💡Hint: Use a for loop with the not operator. This for loop must go through each item in the input_numbers list. Also think about how to add elements of a certain list onto a different list.

# Input: List of numbers with duplicate elements
input_numbers = [1, 2, 3, 4, 3, 2, 5, 6, 1, 7, 8, 9, 7]

# Initialize an empty list to store unique elements
unique_numbers = # your code here

Hint:

  • step 1: loop through all the items in the list:

  • step 2: if the number is not ( command not in) in the unique list

  • step 3: then add it to the unique list using append()

# Iterate through the input list and add unique elements to the unique_numbers list
# step 1
for # your code here:
  # step 2
  if # your code here:
    # step 3
    unique_numbers.append(# your code here)

# Print the list with duplicate elements removed
print("List with duplicate elements removed:", unique_numbers)

6.2. Range function#

range() is a popular built-in Python function that can create a sequence of numbers, which is very handy for a for loop. Below are three different ways of using it.

syntax

Description

range(start, stop, step)

sequence of numbers from start to (stop-1) incremented by ‘step’

range(start,stop)

sequence of numbers from start to (stop-1) incremented by 1

range(stop)

sequence of numbers from 0 to (stop-1) incremented by 1

Here are some examples of using the range() function to print the numbers 0 to 2:

for num in range(0,3,1):
  print(num)

print('\n') # just to print an empty line

for num in range(0, 3):
  print(num)

print('\n') # just to print an empty line

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

Here is another example where range is used to create indices that allow us to both access and modify a list.

# multiply each item in the list by 10, update the list with the new value and print it
grade_list=[6, 5.5, 8, 4, 9.5, 9]

for i in range(len(grade_list)):
  grade_list[i]=grade_list[i]*10
  print(grade_list[i])

print(grade_list)

Note: Here we are directly reassigning values to items on the grade_list. That’s why it changes at the end.


6.2.1. Exercise: Number printer (Optional)#

Write a Python program to display the numbers within the range of 0 to 10.

Hint: use a for loop and the range function, like in the previous examples.

# Display the integers from 0 to 10:

# Multiple equivalent uses of the `range()` function are possible.
# Any of the following three suffices:
for i in # your code here:
  print(i)

6.2.2. Exercise: Odd number printer#

Now, write a Python program to display the odd numbers within the range of 0 to 11 using for loop.

# Display the odd numbers between 0 and 11, including 11:

for # Your code here:
  # Your code here

6.2.3. Exercise: Pyramid pattern generator#

Create a program that generates the following pattern, using a for loop and the range() function:

The result should look something like this:
##
####
######
########
##########

💡 Hint: to create “####” which includes 4, “#” charachters you can use "#"*4

# Initialise your variable:
num_chars = 0 # Your code here

# Write the pattern generator using a for loop and the range() function:
# your code here

Now also add the other half to finish the pyramid:

The result should look something like this:
##
####
######
########
##########
########
######
####
##
# Copy and paste your first half of the pyramid here:
# your code here

# Write the mirrored half of the pyramid here:
# your code here

6.2.4. Exercise: Fibonacci sequence#

Write a Python program to generate and display the Fibonacci Sequence up to the \(n^{th}\) term. Allow the user to input the value of n.

Explanation of the Fibonacci Sequence: The Fibonacci sequence is a series of numbers where each number (known as a Fibonacci number) is the sum of the two preceding ones. It starts with 0 and 1. The sequence goes as follows: 0, 1, 1 (=0+1), 2 (=1+1), 3 (=2+1), 5 (=2+3), 8 = (=3+5), 13, 21, 34, and so on. Each subsequent number is obtained by adding the previous two numbers. Example: if n = 5 then the output sequence should be [0, 1, 1, 2, 3]

# To get a feeling for how the Fibonacci Sequence works, let's make one with n = 5 terms.

# Initialize the first two terms of the Fibonacci Sequence
fibonacci_sequence = [0, 1]

# In order to get the third number, you should add the previous two terms together
first_number = # Your code here
second_number = # Your code here

third_number =  # Your code here

# Let's print the third number
print(third_number)
# Now, add the newly obtained number to the list
fibonacci_sequence.append(# your code here)

# Let's print the list with this additional number
print(fibonacci_sequence)
# Repeat this for the fourth and fifth numbers
fibonacci_sequence.append(# your code here)
fibonacci_sequence.append(# your code here)

# Let's print the sequence
for term in fibonacci_sequence:
    print(term, end=" ")

Now that you have a feeling for how the Fibonacci sequence works, let’s generalise our program.

# Initialize the first two terms of the Fibonacci Sequence
fibonacci_sequence = [0, 1]

# Input: Value of n
n = # Enter the value of n
# Generate the Fibonacci Sequence up to the nth term
for i in range(2, n):
    # add the last two items in the list, that is item at [i-1] an d[i-2]
    # your code here
    # add the calculated terms to the list
    # your code here
# Display the Fibonacci Sequence
print("Fibonacci Sequence up to the", n, "term:")
for term in fibonacci_sequence:
    print(term, end=" ")

6.3. While loop#

A while loop allows us to run a block of code as long as a condition is true. You can see the correct syntax in the code below:

i=0
while i<=5:
  print ("i =",i)
  i=i+1

Infinite loop: Note that if you don’t update your statement (in this example the value of i) your loop will run indefinitely! An example of how an infinite loop can be prevented (in a different scenario than the previous one) is shown in the code below:

i=0
while i>=0:
  print(f"i = {i}")
  i=i+1

  if i>10:  # Note that without this break statement,
    break   # the code would keep running indefinitely

6.4. Break and continue statements#

With break and continue statements we can interrupt the iterations in a loop. Here is how:

  • with the continue statement we can stop the current iteration, and continue with the next. Note that only the statements after the continue command are ignored, not the whole block.

  • with break we can stop the whole loop.

i=0
while i<5:
  i=i+1
  if i==3:
    continue
  print (i)
i=0
while i<5:
  i=i+1
  if i==3:
    break
  print (i)

6.5. else in a loop#

You can also combine a loop with an else statement, which will be executed if the loop statement is not true.

i=0
while i<5:
  print ("i is =",i)
  i=i+1
else:
  print ('end')

6.6. Comparison example for the while and for loop#

There may be cases where you can choose between using the for loop and the while loop to achieve the same goal. You can see an example program below calculating the sum of thr numbers from 1 to 5.

# using for loop
total = 0

for number in range(1, 6):
    total += number

print(f"Sum using for loop: {total}")
# using while loop
total = 0
number = 1

while number <= 5:
    total += number
    number += 1

print(f"Sum using while loop: {total}")

6.6.1. Exercise: Pattern generator with while loop#

Develop a program that generates the following pattern, this time using a while loop:

The result should look something like this:
##
####
######
########
##########
# your code here

6.6.2. Exercise: math challenge#

Develop a Python program that engages the user in a math challenge. The program requests the user to calculate the result of a given math operation, such as “What is the result of 32 * 4?” (or maybe something more difficult.) The program then verifies if the user’s answer is correct. If the answer is correct, a “Good job!” message is displayed, and the program concludes. However, if the answer is incorrect, the user is granted two more attempts. The program first displays the message “Wrong! You have [remaining_attempts] left!” and repeats the process. If the user’s response remains incorrect after the third attempt, the program prints the message “You need more practice!”

Step 1: Here we break the problem into simpler steps, let’s start with printing the question and defining variables with correct answer and number of attemps

correct_answer = 32*4
remaining_attempts = 3

Step 2: Without considering the number of attempts let’s just check the answer and implementing the “Good job!” message if the answer is correct and the “Wrong! you have [remaining_attempts] left!” message if it is incorrect.

# Implement the condition for displaying the "Good Job!" message
user_answer= # Enter the float result of 32*4

# check if the answer is correct or not
if # your code here:
    print("Good Job!")
else:
    remaining_attempts = # your code here
    print(f"Wrong! you have {remaining_attempts} attempts left!")

Now, using the previous code, write the remainder of the program. Note that: 1- we need to use a while loop to repeat step 2 while the number of remaining attempts is > 0.

2- if the answer is correct we don’t need to repeat the while loop so we break the loop after printing the “good job message”

3- if the answer is wrong, we print the “Wrong! …” message and decrease one from the remaining attempts

4- if there is no remaining atteps we print “you need more practice!” , that should be in the else statement of the while loop

correct_answer = 32*4
remaining_attempts = 3

# Implement the conditions for each of the three cases of remaining_attempts
while # your code here:

  user_answer=# your code here

  if # your code here:
    print(# your code here)
    break

  else:
    # your code here
    print(f"Wrong! you have {remaining_attempts} attempts left!")

else:
  print(# your code here)

6.7. Extra loop techniques#

When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.

To loop over two or more sequences at the same time, the entries can be paired with the zip() function.

# using enumerate
for i, v in enumerate(['paper', 'scissors', 'rock']):
  print(i, v)
# using zip
prompts = ['Tell me about a skill you enjoy:', 
           'What would you love to be in another life?', 
           'Which time of year lifts your mood?']
responses = ['I really enjoy woodworking.', 
             'Probably a deep-sea explorer.', 
             'Spring always brings me energy.']

for prompt, response in zip(prompts, responses):
      print(f"{prompt} {response}") 

6.8. List comprehension#

Python provides us with more efficient ways (in time and space) to create a list from existing lists or a more compact way of writting for loops for lists, that is called list comprehension. The general syntax is as follows:

new_list = [ statement(items) for item in old_list if condition ]

Here are some examples:

old_list = [0,1,2,3,4,5,6,7,8,9,10]

new_list1=[item*10 for item in old_list]
new_list2=[item for item in old_list if item%2==0]

print("old_list= ",old_list)
print("new_list1= ",new_list1)
print("new_list2= ",new_list2)

As you can see, these can also be done using for loops, and if-statements, and the append function, but this is more efficient.

6.8.1. 7.1. Exercise: Squares#

Create a list called numbers with the values: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. Next, using list comprehension, create a new list called squares that contains the squares of each number in the numbers list and print it.

#  A
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

#  B: List comprehension to calculate squares
squares = # your code here

#  C
print("Squares:", squares)

6.8.2. 7.2. Exercises: Primes#

Task: Write a Python program that prompts the user to input an integer number between 0 and 100. The program should then determine if the entered number is a prime number and provide an appropriate message.

Program description:

  1. Prompt the user to enter an integer number between 0 and 100.

  2. Check if the entered number is within the specified range (0 to 100). If not, display an “out of range” message.

  3. If the number is within the range, implement an efficient algorithm to determine if it’s a prime number or not.

  4. Print an appropriate message based on whether the entered number is prime or not.


The decision tree below can help you create the algorithm to determine if a number is prime.

print-its-prime.png

# Get user input
number = # Enter an integer between 0 and 100
# creating a variable to store the result, it's by default false
is_prime = False

# Check if the number is within the specified range
if 0 <= number <= 100:                                 # If the number is between 0 and 100, inclusive
    ###
    if number <= 1:                                    # There is no number smaller or equal to 1 that is prime
        is_prime = # your code here
    else:
        is_prime = # your code here                              # Assume the number is prime until proven otherwise
        for i in range(2, # your code here):     # Check divisors from 2 to the square root of the number
            if number % i == 0:                        # If any number evenly divides the input, it's not prime
                is_prime = # your code here
                break

    ## print the message
    if is_prime:                                       # Print the number with a text "... is a prime number" if it is prime
        print(# your code here)
    else:                                              # Print "...is not prime" if it is not prime
        print(# your code here)

else:                                                  # If the number isn't between 0 and 100, print "number is out of the specified range"
    print(# your code here)