Aller au contenu

TP sur les boucles (Microbit)⚓︎

A LIRE : Rappel sur les boucles

Répétition

Pour répéter une intructions la syntaxe est la suivante:

instruction # précédant les répétitions
for var in range(n): # n est le nombre de répétitions, var est la variable prenant toutes les valeurs successivement entre 0 et n - 1
    instruction # à répéter
    instruction #   à répéter
insctruction # suivant les répétitions

exemple de boucle for

Le programme suivant:
for n in range(3):
    print(n)
Affichera:
0
1
2

exemple de boucle for avec plusieurs instructions

Remarque : toutes les instructions qui sont indentées "font parties" de la boucle for

Le programme suivant:
for loop in range(3):
    print("Hello")
    print("world")
print("End")

 

Affichera:

Hello
world
Hello
world
Hello
world
End

Les différents range

  • range(a, b) la variable va alors de a à b - 1.

range(a, b)

Le programme :

for var in range(2, 6):
    print(var)

Affiche :

2
3
4
5

  • range(a, b, p) la variable va alors de a à b - 1 de p en p.

range(a, b, p)

Le programme :

for var in range(1, 6, 2):
    print(var)

Affiche :

1
3
5

Pour tous ces exercices, vous travaillerez sur cette plateforme : https://python.microbit.org/v/3

Exercice 1

Compléter le code suivant pour qu'il affiche un compte à rebours

from microbit import *

def compte_a_rebours(nb):
    for i in range(..., -1, -1):
        display.scroll(str(...))
        sleep(200)
        display.clear()

compte_a_rebours(...)

Exercice 2

Compléter le code suivant pour qu'il affiche un compte à rebours de 9 à 0, suivi d'un coeur

from microbit import *

def compte_a_rebours(nb):
    for i in range(..., -1, -1):
        display.scroll(str(...))
        sleep(200)
        display.clear()

def affiche_coeur():
    ...

compte_a_rebours(...)
affiche_coeur()

Exercice 3

Compléter le code suivant pour qu'il:

  • affiche un compte à rebours de 9 à 0.
  • puis affiche un coeur.
  • puis démarre une tache en boucle (afficher son prénom)
from microbit import *

def compte_a_rebours(nb):
    for i in range(..., -1, -1):
        display.scroll(str(...))
        sleep(200)
        display.clear()

def affiche_coeur():
    ...

def tache_en_boucle():
    while ... :
        display.scroll(...)

compte_a_rebours(...)
affiche_coeur()
tache_en_boucle()

Exercice 4

Compléter le code suivant pour qu'il:

  • affiche un compte à rebours de 9 à 0.
  • puis affiche un coeur.
  • puis démarre une tache en boucle :

    • si on le secoue, il affiche son prénom.
from microbit import *

def compte_a_rebours(nb):
    for i in range(..., -1, -1):
        display.scroll(str(...))
        sleep(200)
        display.clear()

def affiche_coeur():
    ...

def affiche_prenom():
    ...

def tache_en_boucle():
    while ... :
        if ... :
            affiche_prenom()

compte_a_rebours(...)
affiche_coeur()
tache_en_boucle()