1. The selective structure If ... Else ...
The selective structure if ...else is used to execute a set of instructions when a condition is met.
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.
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
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!")