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:
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:
This may sound a little puzzling, but hopefully some simple examples will help shed more light.
Analyzing code samples
Now we're going to show you some simple yet complete programs. We won't explain them in detail, because we consider the comments (and the variable names) inside the code to be sufficient guides.
All the programs solve the same problem - they find the largest of several numbers and print it out.
Example :
We'll start with the simplest case - how to identify the larger of two numbers:
# Read two numbers
number1 = int(input("Enter the first number: "))
number2 = int(input("Enter the second number: "))
# Choose the larger number
if number1 > number2:
larger_number = number1
else:
larger_number = number2
# Print the result
print("The larger number is:", larger_number)
The above snipped should be clear - it reads two integer values, compares them, and finds which is the larger.
Example 2:
Now we're going to show you one intriguing fact. Python has an interesting feature, look at the code below:
# Read two numbers
number1 = int(input("Enter the first number: "))
number2 = int(input("Enter the second number: "))
# Choose the larger number
if number1 > number2: larger_number = number1
else: larger_number = number2
# Print the result
print("The larger number is:", larger_number)
Note: if any of the if-elif-else branches contains just one instruction, you may code it in a more comprehensive form (you don't need to make an indented line after the keyword, but just continue the line after the colon.).
This style, however, may be misleading, and we're not going to use it in our future programs, but it's definitely worth knowing if you want to read and understand someone else's programs.
There are no other differences in the code.
Example 3:
It's time to complicate the code - let's find the largest of three numbers. Will it enlarge the code? A bit.
We assume that the first value is the largest. Then we verify this hypothesis with the two remaining values.
Look as the code below:
# Read three numbers
number1 = int(input("Enter the first number: "))
number2 = int(input("Enter the second number: "))
number3 = int(input("Enter the third number: "))
# We temporarily assume that the first number
# is the largest one.
# We will verify this soon.
largest_number = number1
# We check if the second number is larger than current largest_number
# and update largest_number if needed.
if number2 > largest_number:
largest_number = number2
# We check if the third number is larger than current largest_number
# and update largest_number if needed.
if number3 > largest_number:
largest_number = number3
# Print the result
print("The largest number is:", largest_number)
This method is significantly simpler than trying to find the largest number all at once, by comparing all possible pairs of numbers (i.e., first with second, second with third, third with first). Try to rebuild the code for yourself.