In this post, we will learn about if-else and nested if-else in python with an easy and simple example. So let’s start learning what is if-else and nested if-else in python.
what is if-else in python?
if-else is a keyword in python and it is used as a conditional block in which when the condition is true then if block is executed otherwise else block is executed.
Let’s take an example to understand the if-else block in python
number = int(input("ENter a number: "))
if number>5:
print("number is greater then five")
else:
print("number is not greater then five")
Output-1:
ENter a number: 6
number is greater then five
Output-2:
ENter a number: 4
number is not greater then five
Expaination
In the above example, the number
is checked in the if
block, and when a condition is true then code inside the if
block is executed otherwise code inside the else
block is executed.
that means if
block is executed when your condition is true.
Important note while using if-else in python
else
block is always written afterif
block (it is compulsory).- you can write only
if
block. - you can not write only
else
block (it will give an error becauseelse
block is always written afterif
block). - you can write more than one condition in
if
block using logical operators.
Let’s take an example to understand all the above notes of the if-else block.
only if statement
num = int(input("ENter a any number: "))
if num>7:
print("number is greater then seven")
Output:
ENter a any number: 9
number is greater then seven
if a condition is not true then the above code does nothing (Because there is no else block).
only else statement gives error
num = input("ENter your name: ")
else:
print("this is else block")
Output:
Desktop\allinpython\if-else.py", line 2
else:
^
SyntaxError: invalid syntax
else
block is always written after if
block otherwise it will give SyntaxError.
if statement with multiple conditions
num = int(input("ENter a any number: "))
if num>4 and num<6:
print("entered number is five")
else:
print("entered number is not five")
Output-1:
ENter a any number: 6
entered number is not five
Output-2:
ENter a any number: 5
entered number is five
Now i hope so you understand all the basic concept of if-else in python, So it is time to start learning nested if-else in python.
what is nested if-else in python
A if-else statement placed inside another if
or else
statement is know as nesting of if-else.
let’s understand nested if-else with the help of example:
num1 = int(input("Enter any number: "))
if num1>10:
if num1<15:
print("number is less than 15")
else:
print("number is greater than 15")
else:
if num1<5:
print("number is less than 5")
else:
print("number is greater than 5")
Output-1:
Enter any number: 11
number is less than 15
Output-2:
Enter any number: 7
number is greater than 5
Hope this post add some value to your life – thankyou.
Related Post:
if-elif-else in python