Control Structures
Control the execution flow of your programs
Control Structures in Python: Conditionals and Loops
Control structures are fundamental elements of programming that let you control the execution flow of a program. Instead of running instructions in a linear fashion, they allow you to make decisions and repeat actions based on specific conditions. In this tutorial, we will explore the different control structures available in Python.
Conditional Statements (if, elif, else)
Conditional statements let you run code only if certain conditions are met. Python offers several forms of conditional statements.
Simple if Statement
The most basic form is the if statement followed by a condition:
age = 18
if age >= 18:
print("Vous êtes majeur.")
In this example, the message will be displayed only if the age is greater than or equal to 18.
if-else Statement
To run an alternative block of code when the condition is not met, use else:
age = 16
if age >= 18:
print("Vous êtes majeur.")
else:
print("Vous êtes mineur.")
if-elif-else Statement
To test multiple conditions sequentially, use elif (short for “else if”):
score = 75
if score >= 90:
print("Excellent !")
elif score >= 80:
print("Très bien !")
elif score >= 70:
print("Bien.")
elif score >= 60:
print("Passable.")
else:
print("Besoin d'amélioration.")
Python evaluates the conditions in order and runs the block of code corresponding to the first true condition.
Conditional Expressions (Ternary Operator)
Python offers a compact syntax for simple conditional expressions:
age = 20
statut = "majeur" if age >= 18 else "mineur"
print(f"Vous êtes {statut}.")
This expression is equivalent to the full if-else statement.
Loops
Loops let you run a block of code multiple times. Python offers two main types of loops: for and while.
for Loop
The for loop in Python is used to iterate over a sequence (list, tuple, dictionary, set, or string):
# Itération sur une liste
fruits = ["pomme", "banane", "orange"]
for fruit in fruits:
print(f"J'aime les {fruit}s.")
# Itération sur une plage de nombres
for i in range(5): # 0, 1, 2, 3, 4
print(i)
# Itération avec index
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
The range() function is often used with for loops to generate sequences of numbers.
while Loop
The while loop runs a block of code as long as a condition is true:
compteur = 0
while compteur < 5:
print(f"Compteur: {compteur}")
compteur += 1
It is important to make sure the while loop’s condition eventually becomes false to avoid infinite loops.
Loop Control Statements
Python provides special statements to modify the behavior of loops.
break
The break statement exits a loop immediately:
for i in range(10):
if i == 5:
break
print(i) # Affiche 0, 1, 2, 3, 4
continue
The continue statement skips to the next iteration of the loop:
for i in range(10):
if i % 2 == 0: # Si i est pair
continue
print(i) # Affiche uniquement les nombres impairs : 1, 3, 5, 7, 9
else with Loops
Little known but very useful: for and while loops can have an else clause that runs when the loop finishes normally (without a break):
for i in range(5):
print(i)
else:
print("Boucle terminée normalement")
# Avec break
for i in range(5):
if i == 3:
break
print(i)
else:
print("Ce message ne sera pas affiché")
List Comprehensions
List comprehensions offer a concise syntax for creating lists based on existing sequences:
# Créer une liste des carrés des nombres de 0 à 9
carres = [x**2 for x in range(10)]
print(carres) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# Avec condition
pairs = [x for x in range(10) if x % 2 == 0]
print(pairs) # [0, 2, 4, 6, 8]
This syntax can also be used for dictionaries and sets.
Best Practices
Here are some tips for using control structures effectively:
-
Indentation: In Python, indentation is not just a matter of style; it defines the structure of the code. Be consistent with your indentation (4 spaces per level is recommended).
-
Avoid excessive nesting: Too many levels of nesting make code hard to read. Try to refactor your code or use functions to reduce complexity.
-
Use meaningful names for loop variables when it makes sense.
-
Prefer list comprehensions over traditional for loops for simple data transformation operations.
Conclusion
Control structures are essential for writing flexible and powerful Python programs. They allow you to make decisions, repeat actions, and manipulate the execution flow of your programs.
In the next tutorial, we will explore object-oriented programming in Python, which will let you organize your code even more efficiently and modularly.
Comments
Comments are powered by GitHub Discussions
Sign in with GitHub to join the discussion