Operators
We previously covered types and operators to demonstrate how different types support different operations. We now want to show you a more complete list of operators.
Arithmetic Operators
Arithmetic operators take two numbers and produce a result.
| Operator | Example | Result |
|---|---|---|
| + | 7 + 2 | 9 |
| - | 7 - 2 | 5 |
| * | 7 * 2 | 14 |
| / | 7 / 2 | 3.5 |
| ** | 7 ** 2 | 49 |
| // | 7 // 2 | 3 |
| % | 7 % 2 | 1 |
Addition, subtraction, multiplication, and division are straightforward.
Exponentation ** raises the first number to the power of the second. So 7 to
the power of 2 is 49.
Integer division //, also called floor division, gives the integer portion of
a division operation.
Modulation % gives the remainder of a division operation.
All of these operations can be used in the following ways. First, directly using numbers:
if __name__ == '__main__':
print(5 + 7)
Second, within a function:
# within a function
if __name__ == '__main__':
number = 5
print(number + 7)
Third, using variables:
# using variables
if __name__ == '__main__':
number = 5
number = number + 7
print(number)
Comparison operators
| Operator | Example | Result |
|---|---|---|
| > | 2 > 1 | True |
| < | 2 < 1 | False |
| >= | 2 >=2 | True |
| <= | 2 <= 2 | True |
| == | 4 == 4 | True |
| != | 4 != 6 | True |
We use == to check for equal to and != to check for not equal to.