1. The selective structure If ... Else ...
The selective structure if ...else is used to execute a set of instructions when a condition is met.
Syntax
1 2 3 4 |
if(condition): instructions... else: other directions... |
The condition can be any expression that returns a boolean value (True or False). If the condition is True, then the code in the first block (indented after the if statement) is executed. If the condition is False, then the code in the second block (indented after the else statement) is executed.
Example
1 2 3 4 5 |
age = 19 if(age >= 18): print("You are an adult!") else: print("You are a minor!") |
2. The elif statement
The elif statement is generally used when the exception has 2 or more cases to distinguish. In our example above the exception is age < 18 which corresponds to the minor case. But the minor case includes both cases:
- Childhood age < 14
- Adolescence 14 < age < 18
The else statement selects the opposite condition which is age < 18 and therefore cannot distinguish between the two cases childhood and adolescence. So to overcome this problem, we use the elif instruction:
Example: elif statement
1 2 3 4 5 6 7 |
age = int(input('type your age: ')) if(age >= 18): print("You are an adult!") elif(age<15): print("You are too small!") else: print("You are adolescent!") |
Younes Derfoufi
CRMEF OUJDA
-
Tenda Routeur WiFi 6 RX12 Pro, Router Tenda WiFi AX3000 Bi-Bande, 5 * 6dBi Antennes à Haut Puissance, Large Couverture,
€ 57,00 Acheter le livre -
Apprendre Python et Raspberry Pi sur votre nano-ordinateur
€ 29,00 Acheter le livre -
Comprendre les bases de Python- Bill Lubanovic
€ 34,00 Acheter le livre