If Else statements in Python

The if else statement in Python is used to perform the operations based on some specific condition. There are various ways to use if statement in Python.
(1) if statement
(2) if...else statement
(3) if...elif...else statement

(1) if statement: The if statement is used to test a particular condition and if the condition is true, it executes a block of code known as if block.

Syntax
if condition:
    code to be executed if condition is true

Example -
a=5
b=10
if a<b:
    print(a,"is less than",b)

Output will be
5 is less than 10


(2) if...else statement: In if...else statement, the else block is executed when if block becomes false case of the condition.

Syntax
if condition:
    code to be executed if true
else:
    code to be executed if false

Example -
year=2021
if year%4==0:
    print("2021 is leap year")
else:
    print("2021 is not leap year")

Output will be
2021 is not leap year


(3) if...elif...else statement: The if...elif...else statement helps to check multiple conditions and execute the specific block of statements depending upon the true condition among them.

Syntax
if condition:
    code to be executed if this condition is true
elif condition:
    code to be executed if first condition is false and this condition is true
else:
    code to be executed if all conditions are false

Example -
mynum=15
if mynum<10:
    print(mynum,"is less than 10")
elif mynum>10:
    print(mynum,"is greater than 10")
else:
    print("Invalid condition!")

Output will be
15 is greater than 10


0 Comments