Nesting of conditional statements

--Originally published at Hector Martinez Alcantara

Firstly, what’s nesting?

Nesting in programming is to use a function inside the same function.

In the conditional statements is used to make a condition into another condition, but, what’s the diference between nesting a condition and using operators in the conditional statement?

The main advantage that I can notice  is that in every condition you can realize an action and use conditions into another condition, it makes something like a tree of conditional statements that can  be seen as a choice of multiple options, and like a path to reach a special case.

Well that’s how i see it but, it can be replaced with well planned conditions with operators, and remember the zen 0f python, flat is better than nested.

Also I’ve noticed that in python you don’t have a special function to switch an option, like in  C or Java language, or a select case from Visual Basic. So you have to use the conditionals as a switch option.

Lets see some examples of how nesting a conditional statement works.

Example:

x = input("type only one character \n")
if x.isdigit():
 print("Is a number")
 if int(x) > 5:
 print("the number is greater than five")
 elif int(x) < 5:
 print("the number is smaller than five")
 else:
 print("the number is five")
elif x.isalpha():
 print("you have typed letters")
 if len(x) < 2:
 print("you have typed " + str(x))
 else:
 print("you have typed more than one word")
else:
 print("I dont know what you have typed")

Result:

#if you type a 6 or greater
Is a number
the number is greater than five

#if you type a 4 or smaller
Is a number
the number is smaller than five

#if you type a 5
Is a number
the number is five

#if you type any letter
you have typed letters
you have 
<the letter> #if you type more letters you have typed letters you have typed more than one word #if you type anything else I dont know what you have typed

We can see the nesting enter one condition, realize the action, and then it enters to another condition, respecting the order of the conditions.

Thanks for reading.

Special thanks, and more information in Nested if and if-else statementsThe python operators- The python documentation and Python nested IF statements