Python if…else

  • Python

In this article, we’ll learn decision making using python if…else statement. If and Else is the same as we understand in the English language. If this happens, do this else do nothing. This will be required at some point where we want to execute our code if a condition is satisfied.

The complete statement that we’ll use is if...elif...else . Let’s understand this using a very simple example.

a = 1
b = 2

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

Output :

b is greater than a

Now, what if b was not greater than a? What would it print? Will it give an error?
Let’s check this with an example.

a = 2
b = 1

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

Output :

>>

If you thought of same output, you are doing great!!! It will not give you any error and no output.

You also need to make sure of indentation while using any control statement. Without indentation, you’ll receive an error like one below.

a = 2
b = 1

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

Output :

File "main.py", line 5
    print("b is greater than a")
    ^
IndentationError: expected an indented block

Elif statement

An elif statement runs when the previous condition is not met.

a = 1
b = 1

if a > b:
  print("a is greater than b")
elif a == b:
  print("a is equal to b")

Output :

a is equal to b

In the above example, the first condition did not match which is why it moved to the next condition. When the condition matched, the elif block was executed.

Else Statement

Else statement is executed when none of the conditions are met in a one complete decision block. We do not require any condition for else statement. Let’s check this python if else example.

a = 1
b = 2

if a > b:
  print("a is greater than b")
else:
  print("b is greater than a")

Output :

b is greater than a

If…Elif…Else Statement

This complete block allows us to check multiple conditions. If first condition is not met, it will move to the elif block and if all the conditions are not met, else block will execute.

a = 1
b = 1

if a > b:
  print("a is greater than b")
elif b > a:
  print("b is greater than a")
else:
  print("a is equal to b")

Output :

a is equal to b

Nested if statement

You can have an if…else statement inside another if…else statement.

a = 15

if a > 0:
  if a > 20:
    print("a is greater than 20")
  else:
    print("a is less than 20")
else:
  print("a is a negative number")

Output :

a is less than 20