- Author

- Name
- Nelson Silva
- Social
Introduction
Flow control is a fundamental concept in programming. It allows the program to make decisions and execute specific blocks of code based on determined conditions. In Python, the main tools for flow control are the if, elif and else statements.
Understanding if, elif and else
The if Statement
The if checks a condition and, if it is true, executes the subsequent block of code.
age = 18
if age >= 18:
print('You are an adult.')
The elif Statement
The elif (short for "else if") allows you to check multiple conditions after an if.
age = 15
if age < 12:
print('You are a child.')
elif age < 18:
print('You are a teenager.')
The else Statement
The else is executed when all previous conditions (from if and elif) are false. It does not require a condition.
age = 28
if age < 12:
print('You are a child.')
elif age < 18:
print('You are a teenager.')
else:
print('You are an adult.')
Practical Example
Suppose you want to create a program that categorises the review of a product based on a score from 1 to 5.
score = 4
if score == 1:
print('Very bad.')
elif score == 2:
print('Bad.')
elif score == 3:
print('Average.')
elif score == 4:
print('Good.')
else:
print('Excellent.')
Conclusion
The if, elif and else statements offer a powerful and flexible way to control the flow of execution of a program in Python. When used correctly, they can make your code more logical and efficient.