Conditionals#


Questions:#

  • How can programs do different things for different data?

Learning Objectives:#

  • Correctly write programs that use if and else statements and simple Boolean expressions

  • Trace the execution of conditionals


Use if statements to control whether or not a block of code is executed.#

  • An if statement (more properly called a conditional statement) controls whether some block of code is executed or not.

  • Structure is similar to a for statement:

    • First line opens with if and ends with a colon

    • Body containing one or more statements is indented (usually by 4 spaces)

gdp = 49357

if gdp > 10000:
    print('With a GDP of', gdp, ', this is a wealthy country')
With a GDP of 49357 , this is a wealthy country
gdp = 5937
if gdp > 10000:
     print('With a GDP of', gdp, ', this is a wealthy country')

Conditionals are often used inside loops.#

  • Not much point using a conditional when we know the value (as above).

  • But useful when we have a collection to process.

gdp = [5900, 36100, 33700, 7400, 10700]
for g in gdp:
    if g > 10000:
        print(g, 'is wealthy')
36100 is wealthy
33700 is wealthy
10700 is wealthy

Use else to execute a block of code when an if condition is not true.#

  • else can be used following an if.

  • Allows us to specify an alternative to execute when the if branch isn’t taken.

gdp = [5900, 36100, 33700, 7400, 10700]

for g in gdp:
    if g > 10000:
        print(g, 'is wealthy')
    else:
        print(g, 'is poor')
5900 is poor
36100 is wealthy
33700 is wealthy
7400 is poor
10700 is wealthy

Use elif to specify additional tests.#

  • May want to provide several alternative choices, each with its own test.

  • Use elif (short for “else if”) and a condition to specify these.

  • Must come before the else (which is the “catch-all”)

gdp = [5900, 36100, 33700, 7400, 10700]

for g in gdp:
    if g > 30000:
        print(g, 'is very wealthy')
    elif g > 10000:
        print(g, 'is wealthy')
    else:
        print(g, 'is poor')
5900 is poor
36100 is very wealthy
33700 is very wealthy
7400 is poor
10700 is wealthy

Conditions are tested once, in order.#

Python steps through the branches of the conditional in order, testing each in turn — so ordering matters!

For example, here is a grading scheme no student would want used:

grade = 85

if grade >= 70:
    print('grade is C')
elif grade >= 80:
    print('grade is B')
elif grade >= 90:
    print('grade is A')
grade is C

We often use conditionals in a loop to modify the values of variables#

velocity = 5.0
for i in range(5): # execute the loop 5 times
    print('Step', i, ':', velocity)
    if velocity > 20.0:
        print('Moving too fast')
        velocity = velocity - 5.0
    elif velocity < 20.0:
        print('Moving too slow')
        velocity = velocity + 10.0
    else:
        print('Optimal speed')
Step 0 : 5.0
Moving too slow
Step 1 : 15.0
Moving too slow
Step 2 : 25.0
Moving too fast
Step 3 : 20.0
Optimal speed
Step 4 : 20.0
Optimal speed

To trace execution, we can create a table showing the values of i and velocity each time through the loop:

i

velocity

-

5

0

5

1

15

2

25

3

20

4

20

Compound Relations Using and, & or#

Often, you want to check if some combination of things is true. You can combine relations within a conditional using and and or. Here’s an example with GDP per capita and corresponding populations (in millions) for several countries in 2007. Let’s define a “power” index for countries whereby a country is considered “Very powerful” if it is large (pop. > 10 m) and rich (GDP > 10,000); “powerful” if it is large or rich (but not both); ‘or “not powerful” if it is neither large nor rich.

gdp = [5900, 36100, 33700, 7400, 10700, 27538, 36180, 6557]
pop = [3.6,    8.2,  10.4,  4.6,   7.3,  10.7,   0.3,  0.7]

for i in range(5):
    if pop[i] > 10.0 and gdp[i] > 10000:
        print('Country is very powerful')
    elif pop[i] > 10.0 and gdp[i] > 10000:
        print('Country is powerful')
    else:
        print('Country is not powerful')
Country is not powerful
Country is not powerful
Country is very powerful
Country is not powerful
Country is not powerful

Sometimes you may want to combine multiple and/or statements. For example, continuing the example above, we could define further nuance whereby a country could be considered “very powerful” if it has a population > 10 m and a GDP > 10,000, or if it has a GDP > 30,000 regardless of its population size. We could re-write the first conditional statement from the above example as:

if pop[i] > 10.0 and gdp[i] > 10000 or gdp[i] > 30000:
    print('Country is very powerful')

However, this is potentially ambiguous — it could mean either:

  • if population is > 10 and the GDP is either > 10,000 or > 30,000

  • i.e., if pop[i] > 10.0 and (gdp[i] > 10000 or gdp[i] > 30000)

or

  • if the population is > 10 and the GDP is > 10,000, or if the GDP is > 30,000

  • i.e., (if pop[i] > 10.0 and gdp[i] > 10000) or gdp[i] > 30000

Of the above two examples, only the second meets our new definition of “very powerful”. The first example will fail because it only tests if GDP > 30,000 if population is > 10.

Python has a precedence order (“order of operations”) whereby it evaluates and before or. However, just like with arithmetic, you can and should use parentheses (as in the code examples above)whenever there is possible ambiguity. A good general rule is to always use parentheses when mixing and and or in the same condition.


Exercises#

Compound relations#

Try each of the above three examples of combining and and or operators and see how the results differ (or not).

Tracing Execution#

Without executing the code, predict what this program prints. You can then run it to see if your answer is correct.

pressure = 71.9
    
if pressure > 50.0:
     pressure = 25.0
elif pressure <= 50.0:
     pressure = 0.0
        
print(pressure)

Trimming Values#

Fill in the blanks so that this program creates a new list containing zeroes where the original list’s values were negative, and ones where the original list’s values were positive.

original = [-1.5, 0.2, 0.4, 0.0, -1.3, 0.4]
result = ____
for value in original:
    if ____:
        result.append(0)
    else:
        ____
            
print(result)

Initializing#

Modify this program so that it finds the largest and smallest values in the list no matter what the range of values originally is.

values = [-2, 1, 65, 78, -54, -24, 100]

# Initialize accumulator variables as numeric with no value
smallest = None
largest = None

for v in values:
    # test if accumulator variables have a value or are None
    if ____:
        smallest = v
        largest = v
    # If accumulators are not none, test if they should be updated with current value of v
    ____:
        smallest = min(____, v)
        largest = max(____, v)
        
print(smallest, largest)

Follow-Up Questions#

  • What would be a simpler way of finding the smallest and largest values in the list values?

  • What are the advantages and disadvantages of using the method above to find the range of the data?

Identifying Variable Name Errors#

  1. Read the code below and try to identify what the errors are without running it

  2. Run the code and read the error message

    • What type of NameError do you think this is?

    • Is it a string with no quotes, a misspelled variable, or a variable that should have been defined but was not?

  3. Fix the error

  4. Repeat steps 2 and 3, until you have fixed all the errors

for number in range(10):
    # use a if the number is a multiple of 3, otherwise use b
    if (Number % 3) == 0:
        message = message + a
    else:
        message = message + "b"
        
print(message)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[9], line 3
      1 for number in range(10):
      2     # use a if the number is a multiple of 3, otherwise use b
----> 3     if (Number % 3) == 0:
      4         message = message + a
      5     else:

NameError: name 'Number' is not defined

Summary of Key Points:#

  • Use if statements to control whether or not a block of code is executed.

  • Conditionals are often used inside loops.

  • Use else to execute a block of code when an if condition is not true.

  • Use elif to specify additional tests.

  • Conditions are tested once, in order.


This lesson is adapted from the Software Carpentry Plotting and Programming in Python workshop.