Perform basic arithmetic operations.
Operators |
Description |
+ |
Addition |
- |
Subtraction |
* |
Multiplication |
/ |
Division |
// |
Floor Division (returns the integer part of
the division result) |
% |
Modulo (returns the remainder of the
division) |
** |
Exponentiation |
a = 10
b = 3
print (a + b) # 13
print (a - b) # 7
print (a * b) #
30print (a / b) # 3.3333333333333335
print (a % b) # 1
print (a ** b) # 1000
print (a // b) # 3
Comparison Operators:
Compare values and return True or False.
Operators |
Description |
== |
Equal to |
!= |
Not equal to |
< |
Less than |
> |
Greater than |
<= |
Less than or equal to |
>= |
Greater than or equal to |
x = 5
y = 10
print(x == y) # False
print(x != y) # True
print(x < y) # True
print(x > y) # False
print(x <= y) # True
print(x >= y) # False
Perform logical operations and return True or False.
Operators |
Description |
and |
Logical AND |
or |
Logical OR |
not |
Logical NOT |
p = True
q = False
print(p and q) # False
print(p or q) # True
print(not p) # False
Assign values to variables and perform operations in a concise way.
Operators |
Description |
= |
Assignment |
+= |
Add and assign |
-= |
Subtract and assign |
*= |
Multiply and assign |
/= |
Divide and assign |
//= |
Floor divide and assign |
%= |
Modulo and assign |
x = 5
y = 2
x += y # equivalent to x = x + y
print(x) # 7
Perform bitwise operations on integers.
Operators |
Description |
& |
Bitwise AND |
| |
Bitwise OR |
^ |
Bitwise XOR |
~ |
Bitwise NOT |
<< |
Left shift |
>> |
Right shift |
a = 5 # 0101 in binary
b = 3 # 0011 in binary
print(a & b) # 1 (0001 in binary)
print(a | b) # 7 (0111 in binary)
print(a ^ b) # 6 (0110 in binary)
print(~a) # -6 (complement of 0101 is 1010 in binary)
print(a << 1) # 10 (shift left by 1, 01010 in binary)
print(a >> 1) # 2 (shift right by 1, 0010 in binary)
Test whether a value is a member of a sequence.
Operators |
Description |
in |
True if a value is found in the
sequence |
not in |
True if a value is not found in the
sequence |
a = [1, 2, 3]
b = [1, 2, 3]
print(a is b) # False
print(a is not b) # True
Compare the memory locations of two objects.
Operators |
Description |
is |
True if both variables point to
the same object |
is not |
True if both variables do not point to the same object |
a = [1, 2, 3]
b = [1, 2, 3]
print(a is b) # False
print(a is not b) # True
These operators play a crucial role in performing various operations and comparisons in Python. Understanding how to use them effectively is fundamental to writing clear and concise code.
Comments
Post a Comment