Comparisons

Do you still remember what an operator is?

In our homework, we learned some basic arithmetic operators. If we add one more basic operator (// for integer division), our list will look like this:

Symbol Example Description
+, -, *, / 1 + 1 Basic arithmetic
- -5 Negation
//; % 7 // 2; 7 % 2 Integer division, remainder of division
** 3 ** 2 Power (3 to the power of 2)

Python also has other types of operators. Comparison (relational) operators are used to compare values. Try out what they do! (You can try them by using print() in your code, or you can try python's command line.)

Symbol Example Description
==, != 1 == 1, 1 != 1 equal, not equal
<, > 3 < 5, 3 > 5 greater than, less than
<=, >= 3 <= 5, 3 >= 5 Greater or equal, less or equal

Comparison values are called boolean values (after G. Boole). They are used every time we want to know if something is True or False. Boolean types are exactly those two - True and False.

Like all values, True and False can be assigned to variables:

true = 1 < 3  # we have to type it in lowercase now, because True is a reserved word in Python
print(true)

false = 1 == 3
print(false)

Note that to test equality, you have to use two equal signs: 3 == 3. One equal sign assigns a value to a variable, and two equal signs compare two values (of variables).

True and False can be used directly in a program. Just keep an eye on capitalisation.

print(True)
print(False)

Conditions

Write the following into a new file (e.g. if.py):

side = float(input('Enter the side of a square in centimeters: '))
print("The perimeter of a square with a side of", side,"cm is ", side * 4,"cm.")
print("The area of a square with a side of", side,"cm is", side * side, "cm2.")

What happens when you enter a negative number? Does the output make sense?

As we can see, the computer does exactly what it is told and doesn't think about context. You have to do that for it. It would be nice if the program could tell the user who enters a negative number that they entered nonsense. How do we do that?

Let’s try to set a variable that will be True when a user enters a positive number.

Solution

And then we will tell the program to use this variable. For that purpose we will use the if and else statements.

side = float(input('Enter the side of a square in centimeters: '))
positive_number = side > 0


if positive_number:
    print("The perimeter of a square with a side of", side,"cm is", side * 4,"cm.")
    print("The area of a square with a side of", side,"cm is", side * side, "cm2.")
else:
    print("The side must be a positive number!")

print("Thank you for using the geometric calculator.")

So after if, there is a condition which is the expression we'll use for the decision making. After the condition you must write a colon (:). The colon is followed by the commands to be executed if the condition is True.

You need to indent the follow-up lines by 4 spaces each after every colon you use in Python.

Then on the same level as if, write else followed by a colon :. The next lines contain the commands that are executed if the condition is False, and they must also be indented.

Then you then can write other code, which is not going to be indented and that will be executed every time, because the if statement code block has already ended.

The indentation doesn't need to be 4 spaces, you could use 2 or even 11, or you can use the tabulator. The point is that within one block of code, the indentation has to be the same. So if you are working on some project with someone else, you have to agree on indentation for the program to be able to run properly. Most of the people from the Python community agree on 4 spaces.

Other conditional statements

Sometimes the else statement is not necessary. The following program does nothing extra if the number is not equal to zero.

number = int(input('Enter a number, to which I will add 3: '))
if number == 0:
    print('This is easy!')
print(number, '+ 3 =', number + 3)

Sometimes several conditions are needed. For this situation, we have the elif statement (combination of else and if). It's between if and else. You can repeat the elif keyword after the first if, but only one branch will be executed, to be precise: the first one where the conditions are met (they are true).

age = int(input('How old are you? '))
if age >= 150:
    print('And from which planet are you?')
elif age >= 18:
    # This branch will not be executed for "200", for example.
    print('We can offer: wine, cider, or vodka.')
elif age >= 1:
    print('We can offer: milk, tea, or water')
elif age >= 0:
    print('Unfortunately, we are out of baby formula.')
else :
    # If no condition is met from above, the age had to be negative.
    print('Visitors from the future are not welcomed here!')

Winter clothing

The following piece of code is a bit advanced and we won't fully discuss it right now. In order to work with it, you only need to understand that it will load the current temperature in the city of Vienna (written in German as Wien to not confuse with the city Vienna present in the USA) from the internet into a variable:

from urllib.request import urlopen
url = "https://wttr.in/Wien?format=%t"
temperature = int(urlopen(url).read().decode().strip("°C"))

Write a program using if, elif and else which prints whether you will need no jacket, a light jacket or a winter coat depending on the current temperature:

Solution

Rock paper scissors

Ifs can be nested - after an if and its indentation, there can be other if.

pc_choice = 'rock'
user_choice = input('rock, paper, or scissors?')

if user_choice == 'rock':
    if pc_choice == 'rock':
        print('Draw.')
    elif pc_choice == 'scissors':
        print ('You win!')
    elif pc_choice == 'paper':
        print ('Computer won!')
elif user_choice == 'scissors':
    if pc_choice == 'rock':
        print('Computer won!')
    elif pc_choice == 'scissors':
        print('Draw.')
    elif pc_choice == 'paper':
        print('You win!')
elif user_choice == 'paper':
    if pc_choice == 'rock':
        print('You win!')
    elif pc_choice == 'scissors':
        print('Computer won!')
    elif pc_choice == 'paper':
        print('Draw.')
else:
    print('I do not understand.')

Yay, your first game! Congratulations!!!
Now we need to overwrite the pc_choice so it will act randomly. We will talk about how to do this next time.