Account
Categories

If-Elif-Else Statement


Definition:

To check the condition in Python, if the condition is true, the code inside the if block will execute.

If the condition is not true, it goes to the next and checks the condition.

If that condition is true, then the code inside the elif block runs.

If no condition is true, then the code inside the else block runs.

Now you will clearly understand the code logic with the help of the flowchart.

If-Elif-Else Statement Flowchart :

First step: → You will write the program
           |
Second step: → Now you will check the condition (true/false)

If you find "True", then you will go to the "if block"
          |
       Execute Code
If the first condition is "False", then you will check the 
 elif condition.
          |
      If elif is True → Execute Code.
          |
If elif  is also False, then you will go to the "else block"
          |
       Execute Code
          |
       End the program

Syntax:


if condition1:
    # code to execute if condition1 is true
elif condition2:
    # code to execute if condition2 is true
else:
    # code to execute if no conditions are true

Example:


number = 15

if number > 20:
    print("Number is bigger than 20")
elif number > 10:
    print("Number is bigger than 10 but less than or equal to 20")
else:
    print("Number is 10 or less")

Output:

Exercise

Use the if-elif-else statement to check whether number = 15 is bigger than 20, bigger than 10, or 10 or less and print the result using Python.