Mathematical operators and signs
Let’s now talk about mathematical signs and operations in Python. To represent these operations, we will use integer numbers, but all operations also work with decimals / floats. For the basic operations, Python has the following signs:
Sign | Operation | Example | Definition |
---|---|---|---|
+ | Addition | >>> 4+5 9 |
Adds two numbers |
- | Subtraction | >>> 6-3 3 |
Subtracts two numbers |
* | Multiplication | >>> 7*8 56 |
Multiply two numbers |
/ | Division | >>> 12/4 3.0 |
Divide two numbers |
% | Modulus | >>> 63 % 10 3 |
Returns the rest of the division between two numbers |
** | Exponentiation | >>> 5**3 125 |
Exponentiate two values |
// | Floor division | >>> 5**3 125 |
Divide two numbers, returning the floor number of the result |
Below, we will see some code examples, so that you can confirm how each operator works:
print(4 + 5)
print(6 - 3)
print(7 * 8)
print(12 / 4)
print(63 % 10)
print(5**3)
> 9
> 3
> 56
> 3.0
> 3
> 125
There are also comparison signs. These signs will return True
or False
, indicating if that comparison is true or false. Like we saw in the previous chapter, True
and False
are special values, called booleans. Let’s see examples on the comparison signs:
Sign | Comparison | Example | Definition |
---|---|---|---|
== | Equal to | >>> 4 == 5 False >>> 4 == 4 True |
Check if two values are equal |
!= | Not equal to | >>> 6 != 3 True >>> 5 != 5 False |
Check if two values are not equal |
> | Greater than | >>> 9 > 8 True >>> 3 > 5 False |
Check if value before the sign is greater than the one after it |
>= | Greater than or equal to | >>> 10 >= 10 True >>> 13 >= 15 False |
Check if value before the sign is greater than or equal to the one after it |
< | Less than | >>> 63 < 65 True >>> 150 < 140 False |
Check if value before the sign is less than the one after it |
<= | Less than or equal to | >>> 5 <= 5 True >>> 12 <= 8 False |
Check if value before the sign is less than or equalt to the one after it |
And again, some examples below so you can see how all of these looks in Python:
print(4 == 5)
print(4 == 4)
> False
> True
print(6 != 3)
print(6 != 6)
> True
> False
print(9 > 8)
print(3 > 5)
> True
> False
print(10 >= 10)
print(13 >= 15)
> True
> False
print(63 < 65)
print(150 < 140)
> True
> False
print(5 <= 5)
print(12 <= 8)
> True
> False
Conclusion
In this chapter, we saw the operators used in Python for basic mathematical operations and for comparison between values. These should all be pretty simple to understand if you have basic math understanding.