If/Else/Elif in Python

If/Else/Elif in Python

ยท

1 min read

What are Control Flow Statements in Python?

If Statement

If statement allows you to conditionally execute a block of code. it means to check whether the condition is boolean(True or False).

Syntax:

if (condition):
    return statement

Example:

 year=2020
 if year%4==0:
    print("leap year")
 else:
    print("not a leap year")
 #leap year  

Else Statement

Else statement allows you to execute a block of code when if the condition is false. Note that Else statements need to have a corresponding if condition above them, else cannot be used in isolation.

Syntax:

if (condition):
    return statement
else:
    return statement

Example:

 year=2021
 if year%4==0:
    print("leap year")
 else:
    print("not a leap year")
 #not a leap year

Elif Statement

Elif (or) else if statements allow you conditionally execute a block when the (if) condition is false. Note that elif statements need to have a corresponding if condition above them, elif cannot be used in isolation.

Once an if or an elif condition evaluates to True its corresponding block is executed and subsequent elif/else conditions are not even evaluated.

Syntax:

if (condition):
    return statement
elif (condition):
    return statement
else:
    return statement

Example:

a = 5
b = 10
if a>b:
    print("a is greater than b")
elif a<b:
    print("a is less than b")
else:
    print("a is equal to b")
#a is less than b
ย