Understanding if, else, and elif statements

Conditional execution is one of the cornerstones of programming. It allows us to execute one code, but not the other, depending on the condition. This condition is described in Python as an if statement. It is pretty self-explanatory: code within the scope will be executed if the condition is met:

if rain is True:
agenda = 'Stay Home'

Here, if the rain variable is true, the agenda is to stay at home. 

This statement can make functions more flexible. In the following example, if b is equal to 0, we can't use it as a denominator, so we can check the value, and return None instead. As return terminates all the code of the function, the division does not happen:

def percentage(a, b):
if b == 0:
return None

return round(a / b, 2)

On many occasions, there could be more than one outcome of the logical fork. If you need an alternative code to run if the statement is false, you can use the else keyword. The following code checks whether the name is equal to Annie. If the name matches, the code would print a greeting. If, and only if, it does not (which is the case here), an alternative statement (I don't know you...) will be printed:

name = 'Adrian'

if name == 'Annie':
print('Hello Annie!')
else:
print("I don't know you...")

Since the name is not Annie, this code will print the I don't know you... phrase.

We are not just bound by two options either! You can have more than two logical branches, using the elif keyword (which works like an else-if statement).

Consider the following code. Here, we have four logical branches! First, if the name is in the first set of people we know, the code will print a greeting. If not, but the name is in another set, the greeting will be different. The third option checks whether the name is in our blacklist, in which case we'll ignore the person by passing on execution. Finally, as a last resort, the code will state that we don't know the person:

if name in {'Adrian', 'Annie'}:
print('I know you!')

elif name in {'Agnus', 'Angela'}:
print("Hi! I thing we've met somewhere...")

elif name in {'Boris', 'Brunhilde'} :
# don't talk with them
pass
# pass can be used in code when sintaxis requires some code,
# but none is needed

else:
print("I don't think I know you...")

While that is absolutely feasible, we generally don't recommend writing more than one or two elif branches—they are verbose and hard to read and debug; very often, there are better options in terms of structuring the logic.

So far, we have used else/if statements with indentation, but we also can use them on the same line. In the next section, we'll cover how to use if in inline statements.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset