Python If Else Elif



If the condition is true its body will execute otherwise does not execute.

It is used to test the condition and the result is based on the condition.


Syntax 

if  condition  :
    body 

Example

num = int(input("Enter a Number "))
if num > 0:
    print("Number is greater than 0")

Output

Enter a Number 1
Number is greater than 0

Same as we can use the following comparison operators to compare two values


comparison operators
Operator Meaning Example
== Equals if x == y
!= Not equals if x != y
> Greater than if x > y
>= Greater than or equal to if x >= y
< Less than if x < y
<= Less than or equal to if x <= y

 Example 2:  Check given number is positive or negative or zero Using if Condition

num = int(input("Enter a Number "))
if num > 0:
    print("Number is greater than 0")
if num < 0:
    print("Number is less than 0")
if num == 0:
    print("Number is 0")

Output

Enter a Number -1
Number is less than 0

Indentation

Python depends on indentation (whitespace at the beginning of a line) to determine the scope of the code. Other programming languages usually use curly brackets for this purpose.


Example

num = int(input("Enter a Number "))
if num > 0:
print("Number is greater than 0")

Output

IndentationError: expected an indented block

If else statement

If the condition is the true body of if will execute otherwise body of else execute.


Example

num = int(input("Enter a Number "))
if num >= 0:
    print("Number is greater than 0 or 0")
else:
    print("Number is less than 0")

Output

Enter a Number -1
Number is less than 0

Check given number is even or odd

num = int(input("Enter a Number "))
if num % 2 == 0:
    print("Number is Even")
else:
    print("Number is Odd")

Output

Enter a Number 2
Number is Even

If else if ladder statement

It is used to test the condition.

If executes only one condition at a time.

The condition which is true first from the top will execute.


Syntax

if  condition  :
    body1
elif condition:
    body2
elif condition:
    body3
else:
    body4

Example 1

num = int(input("Enter a Number "))
if num > 11:
    print("body 1")
elif num > 5:
    print("body 2")
elif num > 1:
    print("body 3")
else:
    print("body 4")

Output

Enter a Number 2
body 3

else part will execute if all the conditions are false.


Example 2

num = int(input("Enter a Number "))
if num > 11:
    print("body 1")
elif num > 5:
    print("body 2")
elif num > 1:
    print("body 3")
else:
    print("body 4")

Output

Enter a Number -1
body 4

Example 3

marks = int(input("Enter your Marks "))
if marks > 85 and marks <= 100:
    print("Congrats ! you scored grade A")
elif marks > 60 and marks <= 85:
    print("You scored grade B +")
elif marks > 40 and marks <= 60:
    print("You scored grade B")
elif marks > 30 and marks <= 40:
    print("You scored grade C")
else:
    print("Sorry you are fail")

Output

Enter your Marks 54
You scored grade B