In Python, operators are special symbols or keywords used to perform operations on values and variables. They can be categorized into several types:
1. Arithmetic Operators
Used to perform mathematical operations:
+
: Addition-
: Subtraction*
: Multiplication/
: Division%
: Modulus (remainder of division)**
: Exponentiation (power)//
: Floor Division (division that rounds down to the nearest integer)
Example:
a = 10
b = 3
addition = a + b # 13
subtraction = a - b # 7
multiplication = a * b # 30
division = a / b # 3.333...
modulus = a % b # 1
exponentiation = a ** b # 1000
floor_division = a // b # 3
2. Comparison Operators
Used to compare two values:
==
: Equal to!=
: Not equal to>
: Greater than<
: Less than>=
: Greater than or equal to<=
: Less than or equal to
Example:
a = 10
b = 3
equal = (a == b) # False
not_equal = (a != b) # True
greater_than = (a > b) # True
less_than = (a < b) # False
greater_equal = (a >= b) # True
less_equal = (a <= b) # False
3. Logical Operators
Used to combine conditional statements:
and
: Logical ANDor
: Logical ORnot
: Logical NOT
Example:
a = True
b = False
and_result = a and b # False
or_result = a or b # True
not_result = not a # False
4. Assignment Operators
Used to assign values to variables:
=
: Assign+=
: Add and assign-=
: Subtract and assign*=
: Multiply and assign/=
: Divide and assign%=
: Modulus and assign**=
: Exponentiation and assign//=
: Floor division and assign
Example:
a = 10
a += 3 # a = a + 3, now a is 13
a -= 2 # a = a - 2, now a is 11
a *= 2 # a = a * 2, now a is 22
a /= 4 # a = a / 4, now a is 5.5
5. Bitwise Operators
Used to perform operations on binary numbers:
&
: Bitwise AND|
: Bitwise OR^
: Bitwise XOR~
: Bitwise NOT<<
: Left shift>>
: Right shift
Example:
a = 10 # 1010 in binary
b = 3 # 0011 in binary
bitwise_and = a & b # 0010, which is 2
bitwise_or = a | b # 1011, which is 11
bitwise_xor = a ^ b # 1001, which is 9
bitwise_not = ~a # -(a+1), which is -11
left_shift = a << 1 # 10100, which is 20
right_shift = a >> 1 # 0101, which is 5
6. Membership Operators
Used to test if a sequence contains an item:
in
: Returns True if a sequence contains the specified itemnot in
: Returns True if a sequence does not contain the specified item
Example:
numbers = [1, 2, 3, 4, 5]
is_in = 3 in numbers # True
is_not_in = 6 not in numbers # True
7. Identity Operators
Used to compare the memory locations of two objects:
is
: Returns True if both variables are the same objectis not
: Returns True if both variables are not the same object
Example:
a = [1, 2, 3]
b = a
c = [1, 2, 3]
is_same = a is b # True, b references the same object as a
is_not_same = a is c # False, a and c are different objects even though they contain the same dat
0 Comments
Please do note create link post in comment section