2. Operators#

In the previous section, you saw that variables can be assigned different types of values. Such values can be further processed or manipulated by making use of so-called operators: symbols that represent specific actions. They can be applied to values, or to variables representing certain values. The values that are combined with these operators are called the operands.

We will use operators to do calculations and comparisons. We will also learn that certain operators have different uses, depending on the type of operands.

Mathematical operators#

Numerical values can be used in combination with mathematical operators to do calculations:

Symbol

Use

+

Addition

-

Subtraction

*

Multiplication

/

Division

**

“to the power of”

The code below contains a number of examples of how such mathematical operators can be used.

# Firstly, we create two values a and b
# and assign them numerical values

a = 4
b = 3

c = a + b
print(c)
# c now has value 7
c = a * b
print(c)
#c now has value 12 (4 times 3)
c = a - b
print(c)
# c has value 1 (4 minus 3)
c = c+1
print(c)
#c now has value 2
c += 1
print(c)
# c now has value 3.
# c += 1 is a shorthand notation for  c = c + 1
c = a ** b
print(c)
# c now has value 64 
# a multiplied with itself b times: a*a*a

Exercise 2.1#

If a specific hotel charges €90 per night, how much do guests need to pay if they want to book a room for three nights?

tariff = 90

Exercise 2.2#

Try to debug the code in the cell below. Why does Python report an error? What can we do to perform the calculation?

print( "149" + 1 )

Exercise 2.3.#

Declare three numerical variables with arbitrary values. What is the average of these three values?

Exercise 2.4.#

Write code that calculates and prints the number of seconds in seven days. Try to print the result as a sentence, e.g., “Seven days last X seconds.” where X is the result of the calculation.

Boolean operators#

Boolean operators are operators which compare values. Unlike mathematical operators, such comparisons do not return a number, but a value representing either True or False. Such a value is called a Boolean value. You can work with the following Boolean operators:

Operator Description
== equal to
!= not equal to / different from
> greater than
< less than
>= greater than or equal to
<= less than or equal to

There is an important difference between the single equals sign (=) and the double equals sign (==). The single equals sign is the assignment operator. It can be used to associate a value with a variable. The double equals sign is a Boolean operator which tests whether two operands are equal. The exclamation mark and the equals sign (!=) tests whether two operands are different.

The code below demonstrates how such Boolean operators can be used.

print( 3 > 5 )
## prints 'False'
print( 8 <= 10 )
## prints 'True'
print ( (10-5) == (8-3) )
## prints 'True'; both expressions represent value 5

When Boolean operators are combined with operands, as in the examples above, this combination is referred to as an expression. An expression cannot be an independent statement in itself. Such expressions form the building blocks of statements.

Indivual expressions may also be combined with other expressions to form more complicated expressions. To create such compound Boolean expressions you can make use of the operators and and or.

Operator

Function

and

Logical and: both expressions must be True to result in True

or

Logical or: at least one expression must be True to result in True

not

Negation: if the expression is True, the negated expression is False and vice versa

A number of examples can be found below.

print( 6 < 3 and 7 < 8 )
# prints 'False'; 7 < 8 is True, but 6 < 3 is False. they are not both True!
print( 6 < 3 or 7 < 8 )
# prints 'True'. One of the expressions given is indeed true. 
print( not 3 < 6 )
# prints 'False'. 3 < 6 is True; the negation is False. 

These Boolean expressions can be used both with numbers and with strings. When you use the ‘greater than’ operator in combination with two strings, Python will sort the two strings alphabetically and evaluate whether the first string comes before the second string. The expression in the example below will be evaluated as True, because ‘P’ comes after ‘A’ in the alphabet.

print ( 'Pear' > 'Apple')

The equality operator, (==), can be used to test whether two strings have exactly the same characters. The Boolean expression below is evaluated as False.

string_to_test = 'Apple'

print( string_to_test == 'Pear')

Exercise 2.5.#

The variables a, b and c in the cell below have all been assigned value 0. Reassign values to these variables, in such as way that the four boolean expressions that follow are ALL evaluated as True.

a = 0
b = 0
c = 0

print( a < b )
print( b > c )
print( c < a and b > a )
print( b == c or b >= a )

Printing the values of calculations#

As was discussed above, you can use the print() function to communicate the output of your programme. This print() function can only take string variables as input. If you use the print() function in combination with a single numerical value, Python will convert this number to a string automatically.

The situation becomes more complicated when you want to combine strings and numbers. This can be the case when you want to print a longer sentence which includes the results of a calculation based on numeric variables you created earlier. In such a composite sentence the integers in this sentence need to be converted into strings first, via the str() function. It may be accomplished as follows:

a = 5
b = 7

print( str(a) + ' plus ' + str(b) + ' is ' + str( a+b ) )

## This prints '5 plus 7 is 12'

Having to convert all integers to strings may be slightly cumbersome. An alternative solution is to make use of so-called f-strings. The ‘f’ stands for ‘format’. These f-strings have been available since Python 3.6. To create this type of string, you need to place the character ‘f’ immediately before the opening quote of your string. Within the string that is created in this way, it is possible to include one or more curly brackets, containing the name of a variable. The output of such an f-string is a string containing the values of the variabes you refer to in these curly brackets.

The code below gives an example.

a = 5
b = 7

print(a,b)

print( f'Variable a: {a}\nVariable b: {b}')
print( f'{a} plus {b} is {a+b}' )

## This also prints '5 plus 7 is 12'

As a third possibility, you can work with the format() method. This method needs to be appended to the end of the string that you want to print. As parameters, you need to supply the values you want to print. The string to be printed needs to contain sets of curly brackets, on the locations on whch those values need to appear. These brackets function as placeholders. They need to remain empty.

print( '{} plus {} is {}'.format( a , b, (a+b)) )

Exercise 2.6.#

Given an exchange rate of 1.2408 (euros to American dollars), how many dollars can you buy for 150 euros? To do this calculation, you need to multiply the exchange rate with the original amount of money.

Use the in-built round() function to ensure that the floating point number that results from the calculation is shown as an actual amount, indicating the number of cents. The first parameter of round() is the number to be rounded, and the second number is the number of digits beyond the decimal point.

Finally, paste the result into the following sentence: ‘150 euros are worth x dollars’. Replace ‘x’ with the amount of money you calculated.

euros = 150

Exercise 2.7.#

Debug the code below. The code does not contain a syntax error but a semantic error. Do you understand what happens in the code as given?

nr_weeks = "4"
print( f"Number of days in 4 weeks: {nr_weeks*7}" )