3  Operators, built-in functions, if-statements

3.1 Mathematical operations

In Python you can do a wide variety of mathematical operations. A few examples:

summing = 2 + 2
multiply = 2 * 7
power = 2 ** 16
modulo = 13 % 5

print("Sum: ", summing)
print("Multiply: ", multiply)
print("Power: ", power)
print("Modulo: ", modulo)
Sum:  4
Multiply:  14
Power:  65536
Modulo:  3

Once we have data stored in variables, we can use the variables to do calculations.

number = 42
pi_value = 3.14159265358

output = number * pi_value
print(output)
131.94689145036

3.2 Built-in Python functions

To carry out common tasks with data and variables in Python, the language provides us with several built-in functions. Examples of built-in functions that we already used above are print and type.

Calling a function When we want to make use of a function (referred to as calling the function), we type the name of the function followed by parentheses. Between the parentheses we can pass arguments.

Arguments Arguments are used by a function to perform the body of the function with the value of this argument. In the example below type is the function name and pi_value is the argument.

type(pi_value)
float

Other useful built-in functions are abs(), max(), min(), range(). Find more built-in functions here.

max([1,2,3,2,1])
3

3.3 If-statements and comparisons

In programming it is possible to perform certain tasks only when a certain condition is met: Assume we have a table where each row is a person and the table contains a column age. We want to create a new variable age_group which can have the values child and adult based on the value in the column age. We can use an if-statement to decide whether a person is younger than 18 and asign the right value to age_group.

age = 17

if age < 18:
    print('this person is a child')
this person is a child

As you can see, the line print(...) starts with 4 spaces indentation. In Python indentation is very important. Python uses indentation to determine which lines of code belong together. Lines with the same identation are called a code block. We use code blocks to define what should be done in an if-statement, for-loop or in a functions. E.g. after the if condition, all lines with indentation are only performed when the if-condition is met.

num = 99
if num > 100:
    print('This line is only executed when num > 100')
    print('This line is only executed when num > 100')
    
    print('This line is only executed when num > 100')
    
print('This line is always executed')
This line is always executed

It is also possible to specify a task that is performed when the condition is not met using else (note the use of indentation):

age = 17

if age < 18:
    print('this person is a child')
else:
    print('this person is an adult')

print('done')
this person is a child
done

With an if .. else statement we can define one condition. If we need to check more conditions the if ... else statement can be extended with (one or more) elif to specify more tasks that need to be performed on other conditions. These extended if ... else statements always start with if followed by (one or more) elif. When an else statement is included it is always the last statement, it is the default which will be eceuted when all previous comparisons failed.

Order matters: The statements (or conditions) are checked in order from top to bottom and only the task belonging to the first condition that is met is being performed.

num = -3

if num > 0:
    print(num, 'is positive')
elif num == 0:
    print(num, 'is zero')
else:
    print(num, 'is negative')
-3 is negative

If statements often use comparisons to check if a certain condition is met. Comparisons are done with comparison operators such as >, ==.

Along with the > and == comparison operators that we have already used for comparing values above, there are a few more options to know about:

  • > greater than
  • < less than
  • == equal to
  • != does not equal
  • >= greater than or equal to
  • <= less than or equal to

Let’s now play around with comparisons to see how they work in more detail.

4 > 3
True
4 < 3
False
a = 4 > 3
type(a)
bool

As you can see, comparisons return True or False. The data type of these values are bool which is short for boolean values.

If-statements work with boolean values. If the value is True, the task is performed, if the value is False, the task is not performed.

Boolean values can also be assigned to variables:

a = True
b = True
c = False
type(a)
bool

and, or and not are ‘logical operators’, and are used to join two comparisons (or revert a logical expression in the case of not) to create more complex conditions.

and will return True if both expression on either side are True.

a and b
True
a and c
False
4 > 3 and 9 > 3
True

or is used to check if at least one of two logical expressions are True. If this is the case it will return True.

3 > 4 or 9 > 3
True
4 > 3 or 9 > 3
True

In the last three examples you can see that multiple expressions can be combined in a single line of Python code. Python evaluates the expressions one by one. 4 > 3 would return True, 9 > 3 would return True, so 4 > 3 or 9 > 3 would translate to True or True. Because at least one of the expressions on either side of the or operator is True, the whole expression results to True.

The not operator can be used to reverse the Boolean value. If you apply not to an expression that evaluates to True, then you get False as a result. If you apply not to an expression that evaluates to False, then you get True as a result:

not 4 > 3
False

Logical operators bind variables with different strengths. The and is stronger than the or and gets evaluated first in a boolean expression. So a or b and c will be evaluated like a or (b and c), while in (a or b) and c first the value of the or is evaluated and then combined with and c. This leads to a different result.

a = True
b = True
c = False
print("This expression 'a or b and c' evalutes to ", a or b and c)
print("And this is the same as 'a or (b and c)')", a or (b and c))
print("But this expression evaluates '(a or b) and c' first the 'or' and generates:", (a or b) and c)
This expression 'a or b and c' evalutes to  True
And this is the same as 'a or (b and c)') True
But this expression evaluates '(a or b) and c' first the 'or' and generates: False

Now we know how to use comparisons and logical operators to create complex conditions. These complex conditions can be used in if-statements to perform tasks based on these conditions.

if (1 < 0) or (1 >= 0):
    print('at least one the above logical statements is true')
at least one the above logical statements is true

While and is only true if both parts are true

if (1 < 0) and (1 >= 0):
    print('both tests are true')
else:
    print('at least one of the tests is not true')
at least one of the tests is not true

Exercises

Now open the morning_exercises.ipynb notebook from the place where you have stored it (see Installation and setup instruction) and do exercises 0-3.

When you finished the exercises, continue to chapter Data types, if-statements and for loops