THE ‘ELSE’ CONDITION

Now that we can compare two values pretty well – what if we want to do a variety of things depending on different conditions? For example if we wanted to do one thing if their height and shoe size were equal, and if they aren’t then do something else if another condition is met. Well, we can accomplish this using the else statement You can just write else after your first condition and then specify your ‘else’ condition should the first condition not be met.

The syntax of an if … else statement looks like the following:

[python]
if (condition):
statement(s)
else:
statement(s)
[/python]

Example

[python]
"""
When no condition is placed, Python checks if the value is 0
See below for an example
"""
var1 = 100
if var1: #this is the same as the statement if var1!=0
print ("1 – Got a true expression value")
print (var1)
else:
print ("1 – Got a false expression value")
print (var1)

var2 = 0
if var2: #this is the same as the statement if var1!=0
print ("2 – Got a true expression value")
print (var2)
else:
print ("2 – Got a false expression value")
print (var2)

print ("Good bye!")
[/python]

When the above code is executed, it produces the following result −

[python]
1 – Got a true expression value
100
2 – Got a false expression value
0
Good bye!
[/python]

The ‘elif’ Condition

The elif statement allows you to check multiple expressions for TRUE and execute a block of code as soon as one of the conditions evaluates to TRUE.
Similar to the else, the elif statement is optional. However, unlike else, for which there can be at most one statement, there can be an arbitrary number of elif statements following an if.

The syntax for an ‘if … elif… else’ statement is as follows –

[python]
if (condition1):
statement(s)
elif (condition2):
statement(s)
elif (condition3):
statement(s)
else:
statement(s)
[/python]

Let’s use the example from the introduction where the user has to choose between two options. A sample program may look like the following –

[python]
age = int(input("Please enter your age: "))
shoe_size = int(input("Please enter your shoe size: "))

if (age==show_size):
print("Your height is equal to your age!")

elif (age<show_size): print("your="" height="" is="" less="" than="" your="" age!")="" else="" if="" (age="">show_size):
print("Your height is greater than your age!")

else:
print("Something has gone seriously wrong here!")
[/python]

A great example of “daisy chaining” these all up is to create a program which asks for a student’s test score, and then spits out the grade that they got. Try and create such an application yourself and see how you do. One solution to the problem is as follows, however it’s worth noting that repeating this much code should be making your “bad code” sense tingle! It goes against the “Don’t Repeat Yourself” principle of programming, but for now, a solution like this will have to do:

[python]
test_mark = int(input("Please insert your test mark: ")
if (mark >= 90):
print("You got an A+")
print("You Passed! You should really just teach the class")

elif (mark >= 80):
print("You got an A")
print("You Passed! You’re pretty smart you know that?")

elif (mark >= 70):
print("You got an B")
print("You Passed! You have reached the standard level.")

elif (mark >= 60):
print("You got an C")
print("You Passed! Under the standard but a pass none the less")

elif (mark >= 50):
print("You got an D")
print("You Passed … but barely!")

else:
print("You got an F")
print("You Failed!")
[/python]

You Try

Copy the code above and execute it. Does it create the result you expected? Try changing it up to see what output is created.

Check Your Understanding

Before moving to the next section, let’s see how well you know the current material. Complete the tasks listed below and save your file as YourName_IfPractice.py.

  1. What is wrong with the following if statement? Note: There are at least 3 errors.

    [python]
    if age &gt;= 18
    print("You are old enough to vote!")
    print("Have you researched the candidates?")
    otherwise
    print("Sorry, but you are under 18 and will not be able to vote in this election.")
    [/python]

  2. Explain the function of the if, else if, and else statements.
  3. Write a program that will determine the total cost the user will have to pay for tickets to a concert.
    Lets assume they will only want tickets in one of the sections.

    Ticket Section Cost
    Ticket Section Cost
    Floor $150
    Section 100 $75
    Section 200 $50
    Section 300 $35
  4. Create a program that will calculate a hydro bill for a customer based on the following information:
    Amount of Hydro Used Cost
    0 – 10000 watts $100 flat fee
    10001 – 50000 watts $0.02 per watt over 10000 plus $100
    More than 50000 watts $0.05 per watt over 50000, plus $0.02 for the amount used between 10000 and 50000 watts, plus $100

    The user will input the amount of hydro used and the program will output the amount owing including tax.

  5. Write a math question for the user to answer. This will serve as a sort of quiz. The program should:
    • Have 2 variables called ‘num1’ and ‘num2’
    • Set num1 and num2 to a RANDOM number between 0 and 10
    • Create a variable called ‘operation’.
    • Operation will take input from the user if they would like a multiplication (*), addition (+), or subtraction (-) question.
    • Your program will then perform that operation between num1 and num2. That value will be stored in a variable called ‘correct_answer’.
    • Prompt the user to for the correct calculation and store their answer in a variable called ‘userAnswer’
    • Check to see if they are correct

    Look up Random Functions and include it in your program. Be sure to include a comment on how it works.

    Sample Program
    User entry is bolded

    Example 1

    [python]
    Please enter an opertation: <strong>+</strong>
    What is 5 + 7: <strong>12</strong>
    You are correct!
    [/python]

    Example 1

    [python]
    Please enter an opertation: <strong>*</strong>
    What is 10 * 2: <strong>46</strong>
    You are incorrect
    [/python]

Have a look at the solutions once you are finished.