Python if else with examples

By: On:

In this Python tutorial, let us discuss on Python if else statements, how if else statement works in Python.

We will also check:

  • Python if statement
  • Python else statement
  • Python elif statement
  • Python nested if statement

Contents


Python if statement

In python, if statement is used to check whether the statement is true or false and run the code only when the statement is true.

Example:

x = 10
y = 150
if y > x:
print("y is greater than x")

After writing the above code (python if statement), Ones you will print then the output will appear as a “ y is greater than x “. Here, if statement checks the condition and runs the code if it is true.

You can refer to the below screenshot for python if statement.


Python if statement
Python if statement

Python else statement

In python, else statement contains the block of code it executes when the if condition statements are false.

Example:

x = 34
y = 30
if y > x:
print("y is greater than x")
else:
print("y is not greater than x")

After writing the above code (python else statement), Ones you will print then the output will appear as a “ y is not greater than x “. Here, the else statement executes when the if condition is false then the else statement executes.

You can refer to the below screenshot for python else statement.

Python else statement
Python else statement

Python elif statement

In python, the elif statement is used to check multiple expressions if the previous condition is not true then try this.

Example:

x = 21
y = 21
if y > x:
print("y is greater than x")
elif x == y:
print("x and y are equal")

After writing the above code (python elif statement), Ones you will print then the output will appear as an “ x and y are equal “. Here, the elif statement executes when the previous condition is not true, then the elif statement executes.

You can refer to the below screenshot for python elif statement.

Python elif statement
Python elif statement

Python nested if statement

In python, we use nested if statement to check that the first statement evaluates to true and also whether the nested statement also evaluates to true or not.

Example:

x = 25
if x > 12:
print("Above 12,")
if x > 20:
print("and also above 20")
else:
print("but not above 20")

After writing the above code (python nested if statement), Ones you will print then the output will appear as an “ Above 12, and also above 20 “. Here, we have if statements inside if statement.

You can refer to the below screenshot for python nested if statement.

Python nested if statement
Python nested if statement

You may like the following Python tutorials:

In this Python tutorial, we learned about various if else statement in python like:

  • Python if statement
  • Python else statement
  • Python elif statement
  • Python nested if statement

Leave a Comment