--Originally published at TEC GDL 2016
This blog post I will be writing about nesting of conditional statements. I feel like this the exact right timing to cover this part of Python programming because by now I have all the abilities to understand and master it sufficiently.
What “nesting” means in the end, is that as programs become more advanced more and more detailed calculations/tasks need to be executed and you start seeing conditional statements “within” each other. For you to be able to write a code that completes more advanced tasks than just the simple if, else/elif statement and/or for and while loops, you have to start learning about nesting.
So far I did not explain exactly how a nested if statement looks – sorry if it took me some time to get to the point. So here we go:
When there is a situation where you want to check for another condition once the first condition resolves true you use a nested if construct. A loop inside a loop, if you will.
(Taken from: http://www.tutorialgateway.org/python-nested-if/)
The syntax looks like the following:
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
elif expression4:
statement(s)
else:
statement(s)
See below for an example program:
The output for the given code, if the user enters the number 50:
‘Expression value is less than 200’
‘Which is 50’
‘Good Bye’
And that’s also a Good Bye from me!
I hope you understood all my explanations! If this is not the case make sure to send me a message via @tecjames at Twitter or ask a question in the comment section. I’ll be glad to help
See y’all soon!
Best,
James de Tec
Sources:
http://www.programiz.com/python-programming/if-elif-else
https://www.tutorialspoint.com/python/nested_if_statements_in_python.htm
http://www.openbookproject.net/books/bpp4awd/ch04.html