Conditionals Using Runpython - Runpython-IntroProgramming/Course-Syllabus GitHub Wiki

Being able to accept input from the user and print some kind of output is all well and good, but we expect computers to be able to make some decisions once in a while, and this is where conditionals come in to the picture.

The basic idea of a conditional is to look at whether something is true or not, then make a decision based on that. For example, when you are getting dressed to go to school in the morning you might look at the thermometer. Your logic might go something like this:

If the temperature is below 55 degrees (F) 
then wear a fleece, otherwise don't.

To make it easier to see the structure of this decision, we might want to lay out the text a little differently:

If the temperature is below 55 degrees (F) then
    wear a fleece
otherwise
    don't wear a fleece

This is exactly the way Python likes to make its decisions, except it uses some very specific language:

temperature = float(input("What is the temperature outside? "))
if temperature < 55:
    print("You should bring a fleece.")
else:
    print("You don't need to bring a fleece.")

Try this code out yourself in runpython.com to see how it works.

There are several ways of making decisions about objects. The example above used the < symbol, which means "less than". Here are some more:

  • > greater than
  • == is equal to (do NOT use the = symbol: that is used only to assign values!)
  • != is not equal to
  • is is the same object as
  • <= less than or equal to
  • >= greater than or equal to

There are a few other things about the example above that you should know. The code that Python should execute if the condition is true must be indented following the if statement. Likewise with the code that follows the else (and these can consist of more than one line). Any statement that precedes an indented block must end with a colon (or, looking at it another way: any if or else statement must end with a colon).

You can combine conditionals using and and or, thus:

temperature = float(input("What is the temperature outside? "))
weather = input("Is it raining or sunny outside? ")
weather = weather.lower() # change to lower case
if temperature < 55 and weather == "raining":
    print("You should bring a warm raincoat.")
elif temperature < 55 and weather == "sunny":
    print("You should bring a fleece.")
elif temperature >= 55 and weather == "raining":
    print("You should bring an umbrella.")
else: # the only combination left is sunny and temperature >= 55
    print("You should bring sunglasses.")

This example only uses the and keyword. It will decide that the condition is True only if both of the conditions are True. If one of them is False then the whole thing is False. The or keyword (which isn't in this example) decides the condition is True if either of the conditions is True. The whole thing is False only if both of them are False. You can combine conditions using and and or to your heart's content by enclosing combinations of them in parenthesis to control the order in which they are evaluated.

This example also introduced the elif keyword, which lets you chain a series of conditionals together. This construct replaces the switch/case statement that you would be familiar with if you know some older computer languages.

The preceding example is actually fairly inefficient. Compare it to the following:

temperature = float(input("What is the temperature outside? "))
if temperature < 55:
    if weather == "raining":
        print("You should bring a warm raincoat..")
    else:   # if it's not rainy then it must be cold and sunny!
        print("You should bring a fleece.") 
else:   # 55 or warmer
    if weather == "raining":
        print("You should bring an umbrella.")
    else:   # if it's not rainy then it must be warm and sunny!
        print("You should bring sunglasses.")

As these examples get more complicated, it's important to leave clues to yourself and future readers (programs are often written by multiple people and someone may follow in your footsteps) clues to what your thinking was, if it isn't already obvious from the code you've written.

The clues you leave behind are called comments. You can add a comment to the end of any line by typing the "#" character, then followed by a sentence or two that explains what is going on in the code. If you ever write code that is starting to feel sneaky or weird, then that is a clue that you might want to write a comment or two to explain it.

There is yet another way of using conditionals for decision making in Python. Rewriting the previous example yet again:

temperature = float(input("What is the temperature outside? "))
if temperature < 55:
    clothes = "a warm raincoat" if weather == "raining" else "a fleece"
else:  # 55 or warmer..
    clothes = "an umbrella" if weather == "raining" else "sunglasses"
print("You should bring {0}.".format(clothes))

Try this code on your own and play with it until you understand how it works.

These all-in-one-line-conditional-statements are handy if you're simply setting a value to one of two values, depending on the conditional test. For example, it is extremely handy for transforming lists:

>>> temperatures = [12, 46, 24, 67, 80, 26, 64, 24, 45, 40]
>>> howitfeels = ["{0} is Brr!".format(temp) if temp < 35 else temp for temp in temperatures]
>>> print(howitfeels)
['12 is Brr!', 46, '24 is Brr!', 67, 80, '26 is Brr!', 64, '24 is Brr!', 45, 40]

Try this code on your own and play with it until you understand how it works.


Questions

  1. Why does the following code fail? Rewrite it correctly.

    a = 1
    if a = 1:
        print("True")
    
  2. What will the following code print?

    a = 3
    b = 55
    if a == 3 and b == 4:
        print("yes")
    else:
        print("no")
    
  3. What will the following code print?

    a = 3
    b = 55
    if a == 3 or b == 4:
        print("yes")
    else:
        print("no")
    
  4. What do the following expressions evaluate to?

    1. 3 == 3
    2. 3 != 3
    3. 3 >= 4
    4. not (3 < 4)
  5. If a > b evaluates to True, write an expression with a and b that will evaluate to False.

  6. If a == b evaluates to False, write an expression with a and b that will evaluate to True.

  7. If a > b and c == 3 evaluates to True, write an expression with a, b and c that must evaluate to False.