= 3
a = 6
b = a + b * 2
c print(c)
Operators
Operation | Operator | Example | Evaluates to |
---|---|---|---|
Addition | + |
2 + 2 |
4 |
Subtraction | - |
4 - 1 |
3 |
Multiplication | * |
1.5 * 2 |
3.0 |
Division | / |
5 / 2 |
2.5 |
Floor Division | // |
5 // 2 |
2 |
Modulus (remainder of division) | % |
5 % 2 |
1 |
Exponent | ** |
3**3 |
27 |
Resulting types
If any of the operands is a float, result will be a float. Otherwise (both are integer), result is an integer.
However, there is an exception: result of a division (not floor division) is always a float. Careful with that! (why? we’ll see in a moment)
Operator precedence
- Always be careful with expressions using more than one operator! For example:
- This evaluates as \(a + (b \times 2) = 3 + (6 * 2) = 3 + 12 = 15\)
Python operator precedence order:
- Parentheses:
()
- Exponents:
**
- Multiplication, divisions and modulus:
* / // %
- Addition and subtraction:
+ -
- Comparisons:
<= < >= > == != is
(next week) - Boolean
not
(next week) - Boolean
and
(next week) - Boolean
or
(next week)
Operators in strings
- Python also permits using SOME operators with strings. In a metaphorical way…
String Operation | Metaphor | Operator | Example | Evaluates to |
---|---|---|---|---|
Concatenation | Addition | + |
"Hey" + " " + "apple" |
"Hey apple" |
Repetition | Multiplication | * |
"na" * 4 |
"nananana" |
- Other operators are not supported. Multiplication of a string with another string is also not supported. Both wouldn’t make so much sense…
Evaluating operations in strings
It is also possible to evaluate an expression coded as a string. For example:
= "2 * (4 + 6) / 3 - 5"
expression = eval(expression)
result print(result)
1.666666666666667