The Selective Structure If-Else In Python

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

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

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:

  1. Childhood age < 14
  2. 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




 

Younes Derfoufi
CRMEF OUJDA

Leave a Reply