Loading [MathJax]/jax/output/HTML-CSS/fonts/TeX/fontdata.js

Conditional execution: the if statement

If a certain sleepless Python developer falls asleep when he or she counts 120 sheep, and the sleep inducing procedure may be implemented as a special function named sleep_and_dream(), the whole code takes the following shape:

if sheep_counter >= 120: # Evaluate a test expression
   sleep_and_dream() # Execute if test expression is True

You can read it as: if sheep_counter is greater than or equal to 120, then fall asleep and dream (i.e., execute the sleep_and_dream function)

We've said that conditionally executed statements have to be indented. This creates a very legible structure, clearly demonstrating all possible execution paths in the code.

Take a look at the following code:

if sheep_counter >= 120:
   make_a_bed()
   take_a_shower()
   sleep_and_dream()
feed_the_sheepdogs()

As you can see, making a bed, taking a shower and falling asleep and dreaming are all executed conditionally - when sheep_counter reaches the desired limit.

Feeding the sheepdogs, however, is always done (i.e., the feed_the_sheepdogs() function is not indented and does not belong to the if block, which means it is always executed.)

Now we're going to discuss another variant of the conditional statement, which also allows you to perform an additional action when the condition is not met. 

Conditional execution: the if-else statement

We started out with a simple phrase which read: If the weather is good, we will go for a walk.

Note - there is not a word about what will happen if the weather is bad. We only know that we won't go outdoors, but what we could do instead is not known. We may want to plan something in case of bad weather. 

We can say, for example: If the weather is good, we will go for a walk, otherwise we will go to a theater. 

Now we know what we'll do if the conditions are met, and we know what we'll do if not everything goes our way. In other words, we have a "Plan B".

Python allows us to express such alternative plans. This is done with a second, slightly more complex ofrm of the conditional statement, the if-else statement:

if true_or_false_condition:
   perform_if_condition_true
else: perform_if_condition_false

Thus, there is a new word: else - this is a keyword.

The part of the code which begins with else says what to do if the condition specified for the if is not met (note the colon after the word).

The if-else execution goes as follows:

  1. if the condition evaluates to True (its value is not equal to zero), the perform_if_condition_true statement is executed, and the conditional statement comes to an end
  2. if he condition evaluates to False (it is equal to zero), the perform_if_condition_false statement is executed, and the conditional statement comes to an end. 

 

The if-else statement: more conditional execution 

By using this form of conditional statement, we can describe our plans as follows:

if the_weather_is_good:
   go_for_a_walk()
else:
   go_to_a_theater()
have_lunch()

If the weather is good, we'll go for a walk. Otherwise, we'll go to a theatre. No matter if the weather is good or bad, we'll have lunch afterwards (after the walk or after going to the theatre).

Everything we've said about indentation works in the same manner inside the else branch:

if the_weather_is_good:
   go_for_a_walk()
   have_fun()
else:
    go_to_a_theater()
    enjoy_the_movie()
have_lunch()

Nested if-else statements

Now let's discuss two special cases of the conditional statement.

First, consider the case where the instruction placed after the if is another if

REad what we have planned for this Sunday. If the weather is fine, we'll go for a walk. If we find a nice restaurant, we'll have lunch there. Otherwise, we'll eat a sandwich. If the weather is poor, we'll go to the theater. If there are no tickets, ew'll go shopping in the nearest mall. 

Let's write the same in Python. consider the code here: 

if the_weather_is_good:
    if nice_restaurant_is_found:
         have_lunch()
   else:
         eat_a_sandwich()
else:
    if tickets_are_available:
         go_to_the_theater()
   else:
         go_shopping()

Here are two important points: 

  • this use of the if statement is known as nesting; remember that every else refers to the if which lies at the same indentation level: you need to know this to determine how the ifs and elses pair up
  • consider how the indentation improves readability, and makes the code easier to understand and trace. 

The elif statement

The second special case introduces another new Python keyword: elif As you probably suspect, it's a shorter form of else if.

elif is used to check more than just one condition, and to stop when the first statement which is true is found. 

Our next example resembles nesting, but the similarities are very slight. Again, we'll change our plans and express them as follows: if the weather is fine, we'll go for a walk, otherwise if we get tickets, we'll change our plans and express them as follows: If the weather is fine, we'll go for a walk, otherwise if we get tickets, we'll go to the theater, otherwise if there are free tables at the restaurant, we'll go for lunch; if all else fails, we'll return home and play chess. 

Have you noticed how many times we've used the word otherwise? This is the stage where the elfi keyword plays its role. 

Let's write the same scenario using Python: 

if the_weather_is_good:
   go_for_a_walk()
elif tickets_are_available:
   go_to_the_theater()
elif table_is_available:
   go_for_lunch()
else:
   play_chess_at_home()

The way to assemble subsequent if-elif-else statements is sometimes called a cascade.

Notice again how the indentation improves the readability of the code. 

Some additional attention has to be paid in this case:

  • you mustn't use else without a preceding if
  • else is always the last branch of the cascade, regardless of whether you've used elif or not
  • else is an optional part of the cascade, and may be omitted
  • if there is an else branch in the cascade, only one of all the branches is executed
  • if there is no else branch, it's possible that none of the available branches is executed. 

This may sound a little puzzling, but hopefully some simple examples will help shed more light.