Flattening Nested if Statements
Now, let’s see the
and operator in action, starting with nested
It’s not uncommon for one
if statement to be inside another, but sometimes programmers do this just to create a second condition for what might be a single case, as in this example here First, it wants to see if a provided number is bigger than
Then it wants to see if it’s less than
10. The only time it arrives at the calculation part is if both conditions were true. So instead of writing it as nested ifs, which like this isn’t considered the best way of writing code in Python, it’s better to write it as a single
and and connecting the two original conditions.
00:48 This version is much cleaner to read and is the preferred way of writing this statement. Notice again that this program was specifying that a number be within a range of values.
As you might suspect, this is a very common use of the
and operator, but again, not the only one. In the next lesson, you’ll learn a lot more about value ranges in Python.
Become a Member to join the conversation.