Exercice 1:

Ce code affiche les nombres de 0 à 5 (inclus). Le mot clé break a pour effet de sortir immédiatement de la boucle en ignorant la condition de boucle.


Exercice 2:


import math

def calculate_volume(radius: float) -> float:
    return radius * radius * radius * math.pi * 4 / 3

# boucle avec while
i = 1
while i <= 20:
    print(f"Le volume d'une sphère de rayon {i} est {calculate_volume(i)}")
    i += 1

# boucle avec for
for i in range(1, 21):
    print(f"Le volume d'une sphère de rayon {i} est {calculate_volume(i)}")

Exercice 3:


import math

# version simple
def is_prime(n: int) -> bool:
    if n < 2:
        return False
    for m in range(2, n):
        if n % m == 0:  # m est un diviseur de n
            return False
    return True

# version plus optimisée
def is_prime_optimized(n: int) -> bool:
    if n < 2:
        return False
    if n == 2:
        return True
    if n % 2 == 0:
        return False

    square_root = int(math.sqrt(n) + 1)

    for m in range(3, square_root + 1, 2):
        if n % m == 0:  # m est un diviseur de n
            return False
    return True

print("2 est premier? " + str(is_prime(2)))
print("3 est premier? " + str(is_prime(3)))
print("29 est premier? " + str(is_prime(29)))
print("4 est premier? " + str(is_prime(4)))
print("9 est premier? " + str(is_prime(9)))
print("27 est premier? " + str(is_prime(27)))

# plus concis
for i in 2, 3, 29, 4, 9, 27:
    print(f"{i} est premier? {is_prime(i)}")

num_found: int = 0
n: int = 2

while num_found < 10:
    if is_prime(n):
        print(n)
        num_found += 1
    n += 1

Exercice 4:


def show_word(word: str) -> None:
    if len(word) > 0:
        print(f"Mot: '{word}'")

# alternative:
# if word:
# (un string est "vrai" s'il est non vide)

my_string = "This is fun!"

last_space_position: int = -1
next_space = my_string.find(" ")

while next_space != -1:
    word = my_string[last_space_position + 1:next_space]
    show_word(word)

    last_space_position = next_space
    next_space = my_string.find(" ", last_space_position + 1)

last_word = my_string[last_space_position + 1:]
show_word(last_word)
Last modified: Friday, 27 March 2026, 5:39 PM