Nested if else in Python

Nested if-else statements in Python:

Nested if-else statements are used when there are multiple conditions, and for each condition, a different piece of code is to be executed.

Let us take the situation of grading students according to marks. If a student gets above 90, he/she gets A grade, between 80 and 90 B grade, and below that C.

So, let’s write the code for this situation. The variable Student_grade will contain the grade of the student and the variable Student_marks contains the mark of the students.

if Student_marks>=90:
   Student_grade='A'
else:
   if Student_marks>=80:
      Student_grade='B'
   else:
      Student_grade='C'

The above piece of code looks great, but when there are more conditions, nested if-else statements can be quite the headache.

Especially, since the indentation needs to be taken care of properly. Yikes! We don’t want our code to fail because of this. What can we do?

We can use Logical Operators.

Logical Operators:

There are three logical operators that we use – AND (and), OR (or) and NOT(not).

These are used when there are a lot of conditions.

AND and OR operators are used to get logic out of two conditions, whereas NOT reverses a condition. So, both AND and OR need two conditions, and NOT requires only one.

For AND, both the conditions must be true, to get the net result as true, whereas for OR, at least one out of the two conditions must be true for the net result to be true. Take some time to think this through, and trust me it’s quite logical.

Let’s take into consideration the following situation.

Suppose a student is allowed to take part in a competition only when he has completed the course ‘Course A’ and has got A grade in it. Let’s write the code for this situation. The variables used in the code are self explanatory.

if (Student_grade=='A') and (course=='Course A'):
    print('Allowed to go.')
else:
    print('Not allowed.')

Suppose we want to buy a product only if it’s cost is less than 100, or when we have a coupon for it. Let’s write the code for this situation. The variables used in the code are self explanatory. Note how we used the boolean here to check for the coupon condition.

if (product_cost<100) or (product_coupon==True):
   print('Buy the product.')
else:
   print("Don't buy the product.")

There are lots of situations where we can use logical operators to make our work easy. We will use these later on. I suggest you to take some value of the variables and test the above codes, so you can get a hold of the control flow. Also, notice how we used ” and not ‘ in the last print statement.

We will look upon this fact when we discuss strings.

Nested if else in Python