Python 101 - Part 4 - Conditionals in Python, the Return
Posted on 08-02-2022 in Tutoriais • 2 min read
Continuing the article series on Conditional Structures in Python, we will now look at some other ways to use the if
/else
instructions.
I you haven’t seen our previous tutorials, check here:
It is often not possible to solve a computational problem simply with an if
/else
. So we use multiple nested if
/else
sets (one inside the other)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
But, you can see that if you have a very nested structure of conditions, your code will be very messy… imagine thirty if
/else
instructions nested like that? It gets crazy!
So, to solve this problem, we have the if
/elif
/else
construct. The elif
plays the role of the else
sequences that contain an if
. See how the code is much more readable and organized!
1 2 3 4 5 6 7 8 |
|
You can have as many elif
as needed between if
and else
. See this example:
1 2 3 4 5 6 7 8 9 10 11 |
|
The code remains organized and readable, helping you to understand the code!
Probably, at this point, people who know C, C++, java or some other languages ​​must be asking themselves: But where’s the switch?
Actually, python doesn’t have a switch like we have in other languages, and its function is very well fulfilled by the ‘if’/’elif’/’else’ structures. These structures still have advantages over some switch implementations that for example only do integer and single character comparisons.
It is possible to simulate a switch very efficiently and elegantly in Python, but that will be left for a next post with more advanced content.
In the next topic, we’ll talk about Repetition Structures!
Don’t forget to send your questions and opinions in the comments below!
See you in the next post!