Python If Else, If, Elif, Nested if else | Decision Making in Python

FREE Online Courses: Elevate Your Skills, Zero Cost Attached - Enroll Now!

We would have come across a situation where we have to choose between the options based on the situation. What if we want to implement it by coding? Python provided constructs for this purpose. We will learn each of the conditionals in Python in this article like Python if, if else, elif and nested if else. So let us begin.

Conditional Statements in Python

Did you ever get a pop-up message when you forgot to fill any of the fields in a form? We get this message because in the backend the program checks for empty fields. And if it comes across any of them, it alerts, else it submits the form.

Like this, there are many cases where we need to use conditionals while programming to take further steps. For these purposes, Python provides the following constructs:

1. If statements

2. If-else statements

3. Elif ladders

4. Nested if-else statements

We will discuss each of them with examples in the following sections of this article.

Python If statements

If statements take an expression, which is the condition it checks. If the condition is satisfied then it executes the block of code under it, called the body. If the condition is not satisfied then it skips the execution of the body and executes the further code, if any. The syntax is:

If (expression):
    statement1
    statement2
             .
             .
             .

The statements form the body of the if block. It is important to give the gap (tab or four spaces) for the statements, only then the statements will be considered as a part of the body. And this procedure is called indentation.

python If statements

Example of if-statement:

n=4
if n>0:
    print("The number is positive")

Output:

The number is positive

1. Values as expressions

It printed that the number is positive only because the condition ‘n>0’ is True. The expression can even be a number or a string or a sequence. Remember, these are considered True if they are non-empty/ 0 else False. The expression can also be a boolean.

Example of if-statement:

if '1':
    print("Inside the if block")

Output:

Inside the if block

2. Using parentheses for the expression:

We can also enclose the expression in the brackets as shown below.

Example of if-statement:

if('a' in 'abc'):
    print("a is present in the string")

Output:

a is present in the string

3. Giving proper indentation

However, if we do not indent the block of the code, we get an error asking us to indent properly. We also get an error if we don’t add the colon (:) after the expression. The below example shows this.

Example of getting an indentation error:

if(4):
print("Not indented")

if 4
  print("No colon")

Output:

SyntaxError: expected an indented block

SyntaxError: invalid syntax

Python If-else statements

We saw above that if the condition is True then the block of code is executed. What if we want a different action to take place if the expression gives False?

This is the case where we use the if-else statements. If the condition is True, the statements under if block executes, or else, the ones under the else block executes. The syntax is :

If (expression):
    statements
             .
             .
             .
else:
    statements
             .
             .
             .

python If-else statements
Example of if-else statement:

n=1
if n%2==0:
    print("The number is even")
else:
    print("The number is odd")

Output:

The number is odd

1. Giving proper indentation

Again, an important thing to note is the indentation. Look at the below example for more understanding.
Example of getting an error on not indenting:

if 1==1.0:
  print("They are equal")
  else:	

Output:

SyntaxError: invalid syntax

We got an error above because the else cannot be inside the if block, we have to make its indentation aligned to that of the if expression.

2. Writing more than one else block

Another important point is that we cannot have more than one else block. We get a SyntaxError if we use more than one else block for an if-else statement.

Example of getting an error on writing more than one else statements:

n=3
if(n>3):
    print("The number is greater than 3")
else:
    print("The number is less than 3")
else:

Output:

SyntaxError: invalid syntax

Python elif ladder

We saw above that we get an error if we include more than one else statement. So, we can only check for one condition and have only two cases. What if we have wanted to give more than one option?

We can use elif ladder to have more than two cases. It checks the conditions till it reaches that line where the expression is satisfied and executes the corresponding block of code. The syntax is shown below.

If (expression1):
    statements
             .
             .
elif(expression2):
    statements
             .
             .
elif(expression3):
    statements
             .
             .
.
.
.
else:
    statements
             .
             .     

python elif ladder

Example of elif ladder:

n=4
if(n%5==0):
    print("The number is divisible by 5")
elif (n%10==0):
    print("The number is divisible by 10")
else:
    print("The number is neither divisible by 5 nor 10")

Output:

The number is neither divisible by 5 nor 10

1. The syntax rules of elif ladder

Important points to note regarding the syntax are:

1. Indentation: All the statements should have spaces. All the if, elif, and else expressions should not have any space and should be aligned.

2. It is elif, and not else if

3. There should be an expression for every elif

An example of these errors are shown below:

Example of getting an error on using the wrong syntax for elif ladder:

n=3

if n==1:
    print("The number is equal to 1")
    elif:
  

if n<3:
    print("The number is less than 3")
else if:
  

if n>0:
    print(“The number is greater than 0”)
elif:

Output:

SyntaxError: invalid syntax

SyntaxError: invalid syntax

SyntaxError: invalid syntax

2. Can skip the else part

We can skip the else block as shown below.

Example of elif ladder without else block:

ch='A'
if(ch=='a'):
    print("The character is a")
elif(ch=='A'):
    print("The character is A")

Output:

The character is A

Python Nested if-else statements

This is another choice to give more than two cases. In this, we have if-else blocks inside either if or else blocks. These are useful when we have to check a series of conditions. The syntax is as follows.

If (expression):
    Statements of outer if block
    If (expression):
        Statements of inner if block

    else:
       Statements of inner else block
                              .
                              .

else:
    Statements of outer else block
     If (expression):
        Statements of inner if block

    else:
       Statements of inner else block
                              .
                              .

python Nested if-else statements

Example of nested if-else:

n=9
if(n%5==0):
    if(n%3==0):
        print("The number is divisible by both 5 and 3")
    else:
        print("The number is divisible by both 5 and 3")
else:
    if(n%3==0):
        print("The number is divisible by 3 but not 5")
    else:
        print("The number is not divisible by 5 and not divisible by 3")

Output:

The number is divisible by 3 but not 5

As usual, we have to be careful about the indentation.

Python Nested if blocks

We can also have only if blocks one under another. For example,

Example of nested if blocks:

a=1
b=c=1
if(a==b):
  if(a==c):
    print("a,b, and c are equal")

    
a,b, and c are equal

Output:

The number is divisible by 3 but not 5

Single Statement Conditionals in Python

We can write a simple conditional that include only if block in a single line. We can do this by writing the statement of the if besides the colon on the same line. For example,

Example of single-line conditional if blocks:

if('a' in 'aeiou'): print("It is a vowel")

Output:

It is a vowel

Multiple statements in the if block

We can also add more than one statement by separating them using a semicolon as shown below. For example,

Example of single line if blocks with more than one code:

n=1
if(n==1): print('n is equal to 1'); print("The value of n is ",n)

Output:

n is equal to 1
The value of n is 1

Python Interview Questions on Decision Making Statements

Q1. Write a function to check if the person has the right to vote (age is more than or equal to 18 ).

Ans. We can write if-else block with the condition age >= 18 as shown below.

age=18
if(age>=18):
    print("You have the right to vote!")
else:
    print("You are not eligible to vote")

Output:

You have the right to vote!

Q2. Write a function to find the greatest among the three numbers.

Ans. We can use the nested if-else statements to check the highest number. First, we can check the first two numbers in the outer if-else. Then compare the maximum out of these two with the third value in the inner if-else. For example:

a=3
b=-2
c=9

if(a>b):# a is the maximum of the first two
    if(a>c):
        print("a is the highest")
    else:
        print("c is the highest")
else: # b is the maximum of the first two
    if(b>c):
        print("b is the highest")
    else:
        print("c is the highest")

Output:

c is the highest

Q3. Write a program to check if the name of a person exists in a list or not?

Ans. We can use the membership operator as the expression in the if block to check if the elements exist in the list.

Example of finding membership in a list :

list1=['abc','trw','xyz','pqr']
name=’xyz’
if(name in list1):
    print("The name exists in the list")
else:
    print("Sorry, the name doesn't exist in the list")

Output:

The name exists in the list

Q4. Write a function to check if the year is a leap year or not.

Ans. If the year is divisible by 100, then it has to be divisible by 400. And if the year is not divisible by 100 then it has to be divisible by 4, to be a leap year. The following code shows this.

year=2000

if(year%100==0):
    if(year%400==0):
        print("It is a leap year")
    else:
        print("It is not a leap year")
else:
    if(year%4==0):
        print("It is a leap year")
    else :
        print("It is not a leap year")

Output:

It is a leap year

Q5. Write a program to print the triangle as either equilateral or isosceles or scalene, given the sides.

Ans. We can use elif ladder and use the logical operators’ to check multiple conditions.

Example of finding the type of the triangle :

a=3
b=4
c=3

if(a==b and b==c):
    print("Equilateral Triangle")
elif(a==b or b==c or c==a):
    print("Isosceles Triangle")
else:
    print("Scalene Triangle")

Output:

Isosceles Triangle

Quiz on Python Decision Making Statements

Conclusion

In this article, we learned different conditional statements in Python, like if, if-else, elif ladder, and messed if-else. We also learned to write single-line conditionals. Finally, we saw some coding questions.
Hoping that you understood the concepts discussed. Happy learning!

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google | Facebook


2 Responses

  1. Aleena kouser.s says:

    Super test for python

  2. Aleena kouser.s says:

    I am learning for python programming

Leave a Reply

Your email address will not be published. Required fields are marked *