Decision Making statements in Python

There are some situations when we need to make a decision and decide what to do next. We deal with these types of situations with the decision making statements in Python.
Decision-making statements present in Python are:-

  • if statement
  • if..else statements
  • nested if statements
  • if-elif ladder

You can use them with each other according to your need. I have attached an example with all types to provide the best explanation. You can check more from here.

if statement

This type of statement is used to check whether the given condition is True or not. If it’s true then the block of code inside the if statement will execute else not.

Syntax

a = 2
if (a == 2):
    print ('Code inside if block')

Output

Code inside if block

Here the if block is executed and prints out the statement as the condition is satisfied.

if..else statement

If the condition is False then the else block will run. In the above program, if the variable ‘a’ was equivalent to 3 then the condition will not be satisfied. Hence, else block will run.

Syntax

a = 3
if (a == 2):
    print('Code inside if block')
else:
    print('Code inside else block')

Output

Code inside else block

Here the else block is executed and prints out the statement as the condition was not satisfied.

Nested if statement

If we are using the if statements inside one another then they are known as nested if statements.

Syntax

a = 2
b = 1
if (a == 2):
    if (b == 1):
        print ('Code inside nested if block')

Output

Code inside nested if block

Here the nested if statement is executed and prints out the statement as both the conditions are satisfied.

If-elif ladder

Suppose, we need to check more than one condition and wants our program to execute accordingly. Hence, we can use the if-elif ladder in these types of situations.

Syntax

a = 3
if (a == 2):
    print('Code inside if block')
elif (a == 3):
    print('Code inside elif block')
else:
    print('Code insdie else block')

Output

Code inside elif block

Here the elif statement is executed because the condition of first if the statement was not satisfied and the next elif condition was satisfied.

Note:- It’s mandatory to include the else block with elif but not mandatory if we are using only if statements.

Leave a Reply