Exercices Python – Solutions
Exercices Python – Solutions Complètes
Exercice 1 – PGCD
-----------------
a = int(input("Entrer le premier entier positif : "))
b = int(input("Entrer le deuxième entier positif : "))
while b != 0:
a, b = b, a % b
print("Le PGCD est :", a)
Exercice 2 – FizzBuzz
---------------------
for i in range(1, 101):
if i % 3 == 0 and i % 5 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
Exercice 3 – Factoriel et Combinaisons
--------------------------------------
def fact(x):
f = 1
for i in range(1, x+1):
f *= i
return f
n = int(input("Entrer n : "))
k = int(input("Entrer k : "))
fact_n = fact(n)
fact_k = fact(k)
fact_nk = fact(n - k)
C = fact_n / (fact_k * fact_nk)
print("n! =", fact_n)
print("C(n, k) =", C)
Exercice 4 – Fibonacci
----------------------
n = int(input("Entrer un entier n : "))
a, b = 0, 1
print(a)
if n >= 1:
print(b)
for i in range(2, n+1):
c = a + b
print(c)
a, b = b, c
Exercice 5 – Nombres Premiers
-----------------------------
n = int(input("Entrer une valeur n : "))
for x in range(2, n+1):
premier = True
for i in range(2, int(x**0.5) + 1):
if x % i == 0:
premier = False
break
if premier:
print(x)
# Comptage
count = 0
for x in range(2, n+1):
premier = True
for i in range(2, int(x**0.5) + 1):
if x % i == 0:
premier = False
break
if premier:
count += 1
print("Nombre total :", count)
Exercice 6 – Conversion chiffres → texte
----------------------------------------
digits = ["zéro","un","deux","trois","quatre","cinq","six","sept","huit","neuf"]
n = input("Entrer un nombre : ")
texte = ""
for c in n:
texte += digits[int(c)] + " "
print(texte)
Exercice 7 – Somme des carrés
------------------------------
n = int(input("Entrer n : "))
S = 0
for i in range(1, n+1):
S += i*i
F = n*(n+1)*(2*n+1)//6
print("Somme calculée :", S)
print("Somme formule :", F)
Exercice 8 – Diviseurs propres
------------------------------
n = int(input("Entrer un nombre : "))
for i in range(1, n):
if n % i == 0:
print(i)
Exercice 9 – Approximation de e
-------------------------------
def fact(x):
f = 1
for i in range(1, x+1):
f *= i
return f
n = int(input("Entrer une valeur n : "))
e = 0
for i in range(0, n+1):
e += 1 / fact(i)
print("Approximation de e :", e)