Boucles while

Exercice 1

n = 1
somme = 0
while n <= 5:
    somme += n
    n += 1
print(n, somme)

Correction : dérouler dans PyMemViz

Exercice 2

t = [3, 9, 4, 12, 7]
i = 0
nb = 0
while i < len(t):
    if t[i] > 5:
        nb += 1
    i += 1
print(i, nb)

Correction : dérouler dans PyMemViz

Exercice 3

mots = ["azerty", "1234", "secret", "toto"]
i = 0
while i < len(mots):
    if mots[i] == "secret":
        break
    i += 1
print(i, mots[i])

Correction : dérouler dans PyMemViz

Boucles for sur une liste

Exercice 4

prix = [10, 25, 5, 40]
soldes = []
for p in prix:
    soldes.append(p // 2)
print(prix)
print(soldes)

Correction : dérouler dans PyMemViz

Exercice 5

mots = ["python", "est", "un", "langage"]
for pos, mot in enumerate(mots):
    if pos % 2 == 0:
        print(pos, mot.upper())
    else:
        print(pos, len(mot))

Correction : dérouler dans PyMemViz

Exercice 6

notes = [12, -1, 8, -1, 17]
total = 0
nb = 0
for n in notes:
    if n == -1:
        continue
    total += n
    nb += 1
print(total, nb)
print(total / nb)

Correction : dérouler dans PyMemViz

Boucles for sur un dictionnaire

Exercice 7

ages = {"lea": 17, "tom": 16, "ana": 18}
for prenom in ages:
    print(prenom, ages[prenom])
print(len(ages))

Correction : dérouler dans PyMemViz

Exercice 8

panier = {"pain": 2, "lait": 1, "oeufs": 6}
total = 0
for q in panier.values():
    total += q
print(total)
for produit in panier.keys():
    print(produit, end="-")
print()

Correction : dérouler dans PyMemViz

Exercice 9

stock = {"vis": 40, "clou": 0, "boulon": 12, "ecrou": 0}
rupture = ""
for produit, n in stock.items():
    if n == 0:
        rupture = produit
        break
    print(produit, n)
print("rupture :", rupture)

Correction : dérouler dans PyMemViz