Operator
Arithmetic Operator¶
Operator | Name | Description | Example | Output |
---|---|---|---|---|
+ |
Addition | Adds two numbers | 5 + 3 |
8 |
- |
Subtraction | Subtracts the second from the first | 10 - 4 |
6 |
* |
Multiplication | Multiplies two numbers | 2 * 6 |
12 |
/ |
Division | Divides the first by the second (float) | 8 / 2 |
4.0 |
// |
Floor Division | Division with result rounded down | 7 // 2 |
3 |
% |
Modulus | Remainder of the division | 7 % 2 |
1 |
** |
Exponentiation | Raises to the power | 2 ** 3 |
8 |
In [4]:
Copied!
a = 72
b = 5
print(a % b)
a = 72
b = 5
print(a % b)
2
Comparison Operator¶
Operator | Meaning | Example |
---|---|---|
== |
Equal to | 5 == 5 → True |
!= |
Not equal to | 5 != 3 → True |
> |
Greater than | 5 > 3 → True |
< |
Less than | 5 < 3 → False |
>= |
Greater than or equal | 5 >= 5 → True |
<= |
Less than or equal | 3 <= 5 → True |
In [1]:
Copied!
a = 11.5
b = 10
print(a == b)
print(a != b)
a = 11.5
b = 10
print(a == b)
print(a != b)
False True
Logical Operator¶
Operator | Description | Example |
---|---|---|
and |
True if both are True | True and True → True |
or |
True if any is True | True or False → True |
not |
Inverts True/False | not True → False |
In [2]:
Copied!
a = True
b = False
print(a and b)
print(a or b)
print(not a)
a = True
b = False
print(a and b)
print(a or b)
print(not a)
False True False
In [3]:
Copied!
num_1 = 10
num_2 = 20
(num_1 < 15) and (num_2 >15)
num_1 = 10
num_2 = 20
(num_1 < 15) and (num_2 >15)
Out[3]:
True
Operator Precedence¶
Precedence | Operator Type | Operators | Description |
---|---|---|---|
1 | Parentheses | () |
Overrides default precedence |
2 | Exponent | ** |
Power |
3 | Unary | +x , -x , ~x |
Unary plus, minus, bitwise NOT |
4 | Multiply/Divide | * , / , // , % |
Multiplication, division, etc. |
5 | Add/Subtract | + , - |
Addition and subtraction |
6 | Comparison | == , != , > , < , >= , <= |
Compare values |
7 | Logical NOT | not |
Logical negation |
8 | Logical AND | and |
Logical AND |
9 | Logical OR | or |
Logical OR |
In [1]:
Copied!
a = 5
-a
a = 5
-a
Out[1]:
-5
In [ ]:
Copied!
x = 5
y = 10
z = 15
# Precedence: > then and then not
print(not x > 2 and y < 20)
# Use parentheses to control order
print(not (x > 2 and y < 20)) # not(True and True) → False
x = 5
y = 10
z = 15
# Precedence: > then and then not
print(not x > 2 and y < 20)
# Use parentheses to control order
print(not (x > 2 and y < 20)) # not(True and True) → False
False False
In [ ]:
Copied!