Elegant And Efficient Usage of If-Else Clauses | by Mohammed Ayar | Towards Data Science

Take a piece of writing. Remove the cohesive devices (However, Therefore...). And read it. Does it make sense anymore? NO! The same thing applies to code without if-else statements.
Conditional branching is a basic and mandatory programming concept. It flags a reasoning shift. The wise utilization of conditionals results in having a short, maintainable, and readable code.
That said, ever since I started coding, I took it upon myself to dedicate as much time as possible reading both senior and entry levels programmers’ codes. Here I lay the track I follow to demystify advanced code.
towardsdatascience.com
Surprisingly, the more I read the more I notice how great is the gulf between seasoned and beginner programmers. Seniors write code that takes your breath away. Juniors write code that makes you want to tear your hair out.
Verdict: It’s not about the syntax, it’s about how to use the syntax.
In this piece, I shall to the best of my knowledge explain how great programmers leverage the power of if-else clauses.
Remember:
It’s not about the sword it’s about the swordman.
The professor: “Hello everyone, Today we’re going to take a look at one of the important flow control tools: If-else statements. So, please pay attention to this flowchart.”
Me: “Oh, again, flowcharts. It’s time to sleep. Zzzz”.
I must confess. I am not an attentive student. I start yawning whenever professors exceed 15 min of straight speech. Explanations via flowcharts do only catalyze the process. That was a mistake that costs me so much.
Flowcharts are the simplest way to represent a workflow. I am sure that a great part of your conditional branching troubles will be resolved once you digest if-else flowchart.
Here’s what it looks like:
From the diagram, you can see that how if-else is interpreted is fairly easy. It means once an if expression evaluates as true, its body is executed and the rest of the clauses are ignored.
It is critically important that you understand fully the flowchart because missing a single detail may cost you efficient if statements. Don’t worry, we will be discussing this in detail later on in this post.
I’ve been coding for more than 5 years. During this time, I came to realize that there are two types of programmers.
Those who use verbose and loose if-else statements.
Those who use concise and clean if-else statements.
Ironically, while the ‘How’ is different, the ‘Why’ is the same. To demonstrate this, we’ll resolve the problem below using both above perspectives.
Problem:
You’ve got a bunch of credit cards. You want to classify them into “Maybe Mastercard”, “Maybe Visa” or invalid otherwise. A Visa card must have 4 as the first digit and 16 or 13 digits in total. A Mastercard must have 51, 52 ... until 55 as the first two digits and 16 digits in total.
1st group sample code:
ccn = 13fd = 4if ccn == 16 and (fd == 51 or fd == 52 or fd == 53 or fd == 54 or fd == 55):    print("Maybe MASTERCARD")elif (ccn == 13 or ccn == 16) and fd == 4:    print("Maybe VISA")else:    print("INVALID")
Output:
>>> Maybe VISA
2nd group sample code:
ccn = 13fd = 54if ccn == 16 and 51 <= fd <= 55:    print("Maybe MASTERCARD")elif ccn in [13, 16] and fd == 4:    print("Maybe VISA")else:    print("INVALID")
Output:
>>> Maybe VISA
You can see that while both codes do the same task, each one is written differently. The first is verbose and inelegant. The second is concise and appealing. It’s the kind of if-else statements you want to write. But how to do so?
Learn mathematical logic. A good reference is this class from StanfordMake use of arrays whenever there are multiple values to checkRead experienced programmers code
Learn mathematical logic. A good reference is this class from Stanford
Make use of arrays whenever there are multiple values to check
Read experienced programmers code
I am pretty sure that if you abide by these 3 rules. You’ll be writing better if-else statements.
Ternary Operator literally means an operator composed of three parts. These parts are:
Middle part: a condition
Left part: the expression to be executed once the condition is true
Right part: the expression to be executed otherwise
This translates to the flowchart below:
Just like standard if-else statements, you can use the ternary operator to write flat and nested expressions.
Flat
<expression1> if <condition> else <expression2>
Nested
<expression1> if <condition1> else <expression2> if <condition2> else <expression3> .... if <condition(N-1)> else <expressionN>
It saddens me to see that some programmers abuse this operator only because it is shorter than an explicit if-else statement.
The main reason for the ternary operator is to provide a concise medium for value assignment. It is, therefore, better to use the standard control flow tools when it comes to multiple branching instead of using the operator to write nested expressions.
To quote the author of Python PEP 308 conditional expression proposal:
“A Python design principle has been to prefer the status quo whenever there are doubts about which path to take.”
Have you ever wondered what is the difference between a serial if block and anif-else block? For example:
if <expression1>:   statement1if <expression2>:   statement2       .       .       .if <expressionN>:    statementN
and:
if <expression1>:   statement1elif <expression2>:   statement2       .       .       .elif <expressionN>:    statementN
The first time I was introduced to conditional expressions, I didn’t fully understand if-else flowchart. I, as a result, was always using serial if statements since they were always producing expected results. I was wrong!
While in a serial if block, all the conditions are tested, in an if-elseblock the remaining tests are skipped altogether once an if expression evaluates to true. This approach is known as a circuit-breaker behavior and is way more efficient than a serial if block.
That said, when you’re dealing with a case that requires only one condition to be satisfied use if-else if-else statements.
Perhaps we’ve reached the most important section of this post. Nested if-else statements.
The overuse of conditional clauses leads sometimes to deeply nested if-else statements, which are frowned upon by the programming community and regarded as a poor design.
Luckily, there is a way to outmaneuver nested if-else statements. That is decision tables.
To understand how you can make good use of decision tables. We’re going to work on the following code about comparing numbers in respect to 200:
(This sample is a modified version of a code from tutorialspoint)
Output:
Value is less than 200Between 100 and 150It is 125
Oh boy, we’ve got ourselves a load of if-else statements nested on 3 levels. This is a bad code because it’s lengthy, hard to read and to maintain.
Let’s try to flatten out these nested if-else statements.
But before we do that and to maximize learning outcomes, we’re going to do analyze and jot down remarques from the code above.
The first level of if classifies numbers to greater or less than 200The second level of if classifies numbers to less than 100, less than 150, greater than or equal to 150The third level of if prints the number if it’s equal to those in the conditions
The first level of if classifies numbers to greater or less than 200
The second level of if classifies numbers to less than 100, less than 150, greater than or equal to 150
The third level of if prints the number if it’s equal to those in the conditions
Now, we’ll inject remarque n°2 and n°3 into separate functions. print_interval(val) and print_value(val). Then we’ll store the two nested if-else blocks in two dictionaries (Decision tables). The first one to do the classification as per the remarque n°2. The second one to print the number as per the remarque n°3.
With everything in place, we get the following code:
Output:
Value is less than 200Between 100 and 150It is 125
As you can see we managed to get rid of the nested if-else statements by using functions and decision tables. This has allowed us to write a better-designed code. Readable and maintainable.
Ultimately, you can see that we used a mixture of conditional statements, functions, dictionaries rather than abusing if-else . How to manipulate these, however, is up to you and to your own judgment.
In an effort to help you take your conditional branching skills to the next level, we discussed the pitfalls of if-else statements as well as how to bypass them. The information above is the fruit of 5 years of programming. Still, programming is an infinite realm. that’s why they say:
“Programming is a chess game. Easy to learn. Hard to master”.