nested if

In this lesson I will give examples using nested if statement in Python.

Defining nestings means, in a nutshell, that you can insert ifs within other ifs or within the elif or even within the else.

Indentation – nested if statement in Python

What do you need to watch out for when using the nested if statement in Python? Definitely indentation.

Let’s take a trivial example to illustrate how to nest if statement in Python.

We take as input a number a, if it’s positive we display the message ‘a is positive‘, we also check if it is greater than 100 and if it’s true we display the message ‘and it’s also greater than 100‘. Otherwise, if a is not positive, we simply display the message ‘a is negative‘.

Here is a possible solution to the proposed algorithm:


a = int(input('Enter a positive or negative integer:'))

if a >= 0:
   print('a is greater than zero')
   if a> 100:
      print('and is even greater than 100')
   else:
      print('a is negative')

We extend the problem by asking to also display the message that ‘a is not greater than 100’. To do this we need to add an else to the second if.

Here is a possible implementation of the code:


a = int(input ('Enter a positive or negative integer:'))

if a >= 0:
   print('a is greater than zero')
   if a> 100:
      print('and is even greater than 100')
   else:
      print('a is negative')
else:
   print('a is negative')

We add still more messages, for example if the number is negative and is even greater than -100.

Let’s add what was said in the previous code:


a = int(input('Enter a positive or negative integer:'))

if a >= 0:
   print('a is greater than zero')
   if a> 100:
      print('and is even greater than 100')
   else:
      print('a is negative')
else:
   print('a is negative')
   if a> -100:
      print('and is greater than -100')
   elif a == - 100:
      print('and is equal to -100')
   else:
      print('and is less than -100')

And so on. So in Python it is possible to use nested if, taking care to maintain correct indentation.

Having said that, however, the advice remains to use nested ifs in moderation.

These are just very simple examples of the use of nested if statement in Python, in the next lesson I will propose some useful exercises to better understand the concept.

Useful links

Python tutorial

Python Compiler

Install Python

Variables

Assignment operators

Strings

Casting

How to find the maximum of N numbers

Python

Bubble sort

Matplotlib Plot

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *