Tests et Boucles

Author

Ludovic Deneuville

Before starting

  • Download this Jupyter notebook
    • 💡 Click the Jupyter button on the left, at the very bottom of the table of contents, if the file does not download automatically
  • Connect to SSP Cloud and open a Jupyter-python service
    • or another platform (Jupyter ENSAI, Jupyter Lab, Google Colab, Kaggle…)
  • Import the .ipynb file

1 Conditional structures and loops

In this Notebook, we will cover the following topics:

  • if, else statements
  • the for loop
  • the while loop
  • the break and continue statements

2 Conditional structures

We are going to test different Boolean conditions (see Notebook 1) using the keywords: if, else and elif.

The principle is as follows:

if condition1:
    # Code block to execute if condition1 is true
elif condition2:
    # Code block to execute if condition1 is false and condition2 is true
else:
    # Code block to execute if conditions 1 and 2 are false

Remarks:

  • there can be as many elif statements as necessary (between 0 and infinity)
  • the else statement is optional Warning: It is important to respect the syntax, especially the indentation!
a = 12

# Simple if
if a > 5:
    print("variable a({}) is strictly greater than 5".format(a))
a = 3

# if else
if a > 5:
    print("variable a({}) is strictly greater than 5".format(a))
else:
    print("variable a({}) is less than or equal to 5".format(a))
nb_habitants = 750

if nb_habitants < 500:
    print("village")
elif nb_habitants < 10000:
    print("town")
else:
    print("large town")
# Multiple conditions
note_maths = 14
note_info = 20
validation_anglais = True

if note_maths > 10 and note_info > 10 and validation_anglais:
    print("Year validated")
# Cascading conditions

if note_maths > 10:
    if note_info > 10:
        if validation_anglais:
            print("Congratulations, keep it up!")
        else:
            print("Work harder")
    else:
        print("There are 10 types of people, those who are good at computer science and the others")
else:
    print("1+1=2")

3 Loops

Loops are useful for repeating the same operation many times.

For example, if we want to display all the elements of a list, writing as many print statements as there are elements would be rather tedious.

As with conditional structures, it is very important to respect the indentation!

3.1 The for loop

There are several ways to use the for loop. Here are some examples.

It is very common to use the range(start, stop, step) method with loops, which generates a sequence of integers.

  • start: Starting value of the sequence (optional). By default, it is set to 0.
  • stop: Ending value of the sequence (excluded).
  • step: Increment step (optional). By default, it is set to 1.
# Display integers between 1 and 6
for i in range(1, 6):
    print(i)
for i in range(6):
    print(i, i ** 2, sep="\t")
# Iterating over a list
personnages = ["Luke", "Leia", "Han", "Obi-Wan"]

for p in personnages:
    print("Hello " + p)
# Iterating over a list by index

for i in range(len(personnages)):
    print("Character " + str(i) + " : " + personnages[i])

The enumerate() function is used to iterate simultaneously over indices and elements.

It generates a tuple(index, element).

list(enumerate(personnages))
# Iterating over a list using enumerate

for numero, nom in enumerate(personnages):
    print("Character " + str(numero) + " : " + nom)
# Iterating over a string
for char in "Darth Vader":
    print(char, end=" - ")
import time

message = "Hello bunnies"

for i in range(len(message)):
    time.sleep(0.5)
    print(message[i], end="")
ingredients = {'sucre': '100g', 'poire': 2, 'lait': '1L', 'sel': True}

# Iterating over dictionary keys
for cle in ingredients:
    print(cle)

3.2 The while loop

The principle of the while loop is as follows:

  • an entry condition for the loop is defined
  • as long as the condition is satisfied, the code inside the loop is executed
  • and so on, until we exit the loop (or remain stuck in it forever…)
cpt = 5

while cpt >= 0:
    print(cpt, end="...")
    cpt -= 1      # cpt = cpt - 1

print("Boom")
user_input = input("Enter an even number: ")

while int(user_input) % 2 != 0:
    print("This is not an even number.")
    user_input = input("Enter an even number: ")

print("Thank you, you entered an even number.")

Stopping criterion

The main difference with the for loop is the stopping criterion.

In a for loop, this criterion is clear: the loop iterates over the elements of an iterable object, which necessarily has a finite size.

In contrast, in a while loop, this criterion may never be met, and we then end up in an infinite loop…

For example, if we make a mistake in the index variable name, here is the result:

# Use the "Stop" button (black square) in Jupyter to stop the running program
i = 1
j = 1

while i <= 5:
    j = j + 1

Since i = 1 and never changes, the condition i <= 5 is always equal to True.

print(i)
print(j)

3.3 The break statement

Another way to exit a for or while loop is to use the break statement.

The code below shows how this statement can be used:

  • We enter an infinite loop (While true)
  • The only way to exit it is to find the correct number, which leads us to the break

The code also contains try and except statements, which handle the case where the entered value is not numeric.

Note: in the case of nested loops, break only terminates the innermost loop.

import random

nombre_aleatoire = random.randint(1, 20)

print("Enter a number between 1 and 20")

while True:
    nombre_saisi = input()
    try:

        nombre_saisi = int(nombre_saisi)
        if nombre_saisi == nombre_aleatoire:
            break
        elif nombre_saisi < 1 or nombre_saisi > 20:
            print("Between 1 and 20!!!")
        elif nombre_saisi > nombre_aleatoire:
            print("It's lower")
        elif nombre_saisi < nombre_aleatoire:
            print("It's higher")

    except ValueError:
        print("Please enter a valid integer")

print("Congratulations, you found the secret number:", nombre_aleatoire)

3.4 The continue statement

The continue statement allows you to move on to the next iteration of the loop.

In the example above:

  • we enter an infinite loop
  • as long as we do not enter the correct first name, we start again from the beginning of the loop
    • we only exit the loop once we have entered the correct password
votre_prenom = "alice"

while True:
    print("Please enter your first name.")
    prenom = input()
    if prenom != votre_prenom:
        continue

    print("Please enter your password.")

    mdp = input()

    if mdp == "123456":
        break

print("Welcome " + votre_prenom)

4 Exercises

4.1 Exercise 1

Write a program that calculates the sum of the first 10 squared integers.

Write a program that calculates the sum of the first 5 odd squared integers.

# Test your answer in this cell
# Note: with Python, it is sometimes possible to condense the code

sum(i**2 for i in range(1,11) if i%2 == 1)

4.2 Exercise 2

Rewrite the code below using a for loop.

Hint: explore the different uses of the range() method.

cpt = 5

while cpt >= 0:
    print(cpt)
    cpt -= 1      # cpt = cpt - 1

print("Boom")
# Test your answer in this cell

4.3 Exercise 3

Rewrite the following for loop using a while loop.

gamme = ['do', 're', 'mi', 'fa', 'sol', 'la', 'si']

for i, note in enumerate(gamme):
    print("Note number " + str(i) + " of the C major scale is " + note)
# Test your answer in this cell

4.4 Exercise 4

Sort the list below using 2 for loops (without using a built-in sorting method):

  • liste = [34, 7, 20, 12, 50, 23, 16, 28, 6, 11, 19, 13, 26, 8, 9]
# Test your answer in this cell

4.5 Exercise 5

Write a program to calculate the first 10 terms of the Fibonacci sequence using a for loop.

Same question using a while loop.

Reminder: The Fibonacci sequence is defined as follows:

  • the first two numbers are 0 and 1
  • each subsequent number in the sequence is obtained by adding the two preceding numbers
# Test your answer in this cell

4.6 Exercise 6

Calculate the minimum and maximum of the following series of values, without using Python’s min and max functions.

x = [8, 18, 6, 0, 15, 17.5, 9, 1]

# Test your answer in this cell

4.7 Exercise 7

Using for and while loops, iterate over this dictionary and display each student’s average.

notes = {
    "Miranda"  : [16, 5, 8, 12],
    "Celestin" : [19, 1, 7, 10],
    "Hypolyte" : [18, 3, 12],
    "Josephine": [12, 15, 14, 14]
}
# Test your answer in this cell

4.8 Exercise 8

Calculate the mean and variance of the following series of values, without using pre-coded functions:

x = [8, 18, 6, 0, 15, 17.5, 9, 1]

As a reminder, the formulas are:

  • mean: \[\bar{x} = {\frac {1}{n}}\sum_{i=1}^{n}x_{i}\]
  • variance: \[\sigma^2 = {\frac {1}{n}}\sum_{i=1}^{n} (x_{i}-\bar{x})^2\]
# Test your answer in this cell
# To check your results
import numpy as np

# Create an array of numbers
x = [8, 18, 6, 0, 15, 17.5, 9, 1]

print("Mean     : ", np.mean(x))
print("Variance : ", np.var(x))