Python operators
- Arithmetic operators
- Assignment operators
- Comparison operators
- Logical operators
- Identity operators
- Membership operators
- Bitwise operators
Arithmetic operators
Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, etc.
Example.
addition:
a = 10 + 5
print(a)
division:
d = 15 / 2
print(d)
subtraction:
b = 20 - 8
print(b)
multiplication:
c = 3 * 4
print(c)
Assignment operators
Assignment operators are used to assign values to variables:
= : Assigns the value on the right to the variable on the left.
Example:
x = 5
x = x + 1
print(x)
output:6
-= : Subtracts the value on the right from the variable on the left and assigns the result to the variable.
Example:
y = 20
y -= 5 # Equivalent to
y = y - 5
print(y)
output:15
+= : Adds the value on the right to the variable on the left and assigns the result to the variable
Example:
y = 10
y += 5 # Equivalent to y = y + 5
print(y)
Output: 15
Comparison operators
Comparison operators are used to compare values and return boolean results (True or False).
Equal to (==
)
- Checks if two values are equal.
- Syntax:
a == b
- Example:
x = 10
y = 10
print(x == y) # Output: True
Not equal to (!=
)
- Checks if two values are not equal.
- Syntax:
a != b
- Example:
x = 10
y = 5
print(x != y) # Output: True
Greater than (>
)
- Checks if the left value is greater than the right value.
- Syntax:
a > b
- Example:
x = 10
y = 5
print(x > y) # Output: True
Less than (<
)
- Checks if the left value is less than the right value.
- Syntax:
a < b
- Example:
x = 5
y = 10
print(x < y) # Output: True
Greater than or equal to (>=
)
- Checks if the left value is greater than or equal to the right value.
- Syntax:
a >= b
- Example:
x = 10
y = 10
print(x >= y) # Output: True
Logical Operators
Logical AND (and
)
- Returns
True
if both operands areTrue
. If either operand isFalse
, the result isFalse
. - Syntax:
a and b
x = True
y = False
result = x and y # Result is False because y is False
print(result)
Logical OR (or
)
Returns True
if at least one of the operands is True
. If both operands are False
, the result is False
.
Syntax: a or b
x = True
y = False
result = x or y # Result is True because x is True
print(result)
Logical NOT (not
)
Returns True
if the operand is False
and False
if the operand is True
. It inverts the Boolean value of the operand.
Syntax: not a
x = True
result = not x # Result is False because x is True
print(result)