Python If-Else Statement

if-else statement in python

Python If-Else Statement : Decision making is the most important aspect of almost all the programming languages. As the name implies, decision making allows us to run a particular block of code for a particular decision. Here, the decisions are made on the validity of the particular conditions. Condition checking is the backbone of decision making.

If Statement : 

The if statement is used to test a specific condition. If  the condition is true, a block of code (if-block) will be executed.

Example

a = 33
b = 200
if b > a:
print(“b is greater than a”)


Output:

b is greater than a

Elif Statement: 

The elif keyword is pythons way of saying “if the previous conditions were not true, then try this condition”.

Example

a = 33
b = 33
if b > a:
print(“b is greater than a”)
elif a == b:
print(“a and b are equal”)


Output:

a and b are equal

Else Statement:

The else keyword catches anything which isn’t caught by the preceding conditions.

Example:

a = 200
b = 33
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")
else:
  print("a is greater than b")

Output :

a is greater than b

Nested if Statement:

Nested if statements enable us to use if ? else statement inside an outer if statement.

Example:

a = 33
b = 200
if b > a:
  print("b is greater than a")

Output:

i is smaller than 15
i is smaller than 12 too

if-elif-else ladder

Here, a user can decide among multiple options. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.

Example:-

# Python program to illustrate if-elif-else ladder 
#!/usr/bin/python 
   
i = 20
if (i == 10): 
    print ("i is 10") 
elif (i == 15): 
    print ("i is 15") 
elif (i == 20): 
    print ("i is 20") 
else: 
    print ("i is not present") 

Output:

i is 20

Short Hand if Statement :

Whenever there is only a single statement to be executed inside the if block then shorthand if can be used. The statement can be put on the same line as the if statement.

Example:

# Python program to illustrate short hand if 
i = 10
if i < 15: print("i is less than 15") 

Output:

i is less than 15

Short Hand Python If-Else Statement :

This can be used to write the if-else statements in a single line where there is only one statement to be executed in both if and else block.

Example:

# Python program to illustrate short hand if-else 
i = 10
print(True) if i < 15 else print(False) 

Output:

True

Recommended Posts:

Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *