Section Summary
Key Takeaways
An EXPRESSION is a combination of values (or variables, operators, calls to functions) which evaluates to a value eg
( 1 + 2 )
Operators are special symbols or keywords which are able to operate on the values and perform (mathematical) operations eg the
*
operator multiplies 2 valuesx * y
Arithmetic operators
(+, -, *, /)
returns a float if ONE of the values is of the float type%
(modulus - divides left operand by right operand and returns the remainder of the operation eg. 5 % 2 = 1**
Exponentiation - left operand raised to the power or right operand eg.2 * *3 = 8
/ / Floor/integer division - returns a number resulting from division, but rounded DOWN to the nearest whole number eg
3 // 2.0 = 1.0
A unary operator is an operator with only 1 operand eg
-1
or+3
A binary operator is an operator with 2 operands eg.
4 + 5,
or12 % 5
Some operators act before others - the hierarchy of priorities
unary
+
and-
have the highest prioritythen **, then * , / , and % and then the lowest priority: binary
+
and-
Sub-expressions in parenthesis are always calculated first eg
15 - 1 * (5 * (1 + 2)) = 0
The exponentiation operator uses right-sided binding eg
2 ** 2 ** 3 = 256
Exercise 1
What is the output of the following snippet? print((2 ** 4), (2 * 4.), (2 * 4))
16 8.0 8
Exercise 2
What is the output of the following snippet? print((-2 / 4), (2 / 4), (2 // 4), (-2 // 4))
-0.5 0.5 0 -1
Exercise 3
What is the output of the following snippet? print((2 % -4), (2 % 4), (2 ** 3 ** 2))
2 // -4 = -1 --------> Remember floor division -ive so lowest rounding off!!
-1 * -4 = 4
2 - (4) = -2
-----
2
512
Last updated
Was this helpful?