Python opeartors 2
Python opeartors 2
print(5 + 6) # 11
1. Arithmetic operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
5. Bitwise Operators
6. Special Operators
1. Python Arithmetic Operators
Arithmetic operators are used to perform mathematical
operations like addition, subtraction, multiplication, etc. For
example,
sub = 10 - 5 # 5
+ Addition 5 + 2 = 7
- Subtraction 4 - 2 = 2
* Multiplication 2 * 3 = 6
/ Division 4 / 2 = 2
// Floor Division 10 // 3 = 3
% Modulo 5 % 2 = 1
** Power 4 ** 2 = 16
Example 1: Arithmetic Operators in Python
a = 7
b = 2
# addition
print ('Sum: ', a + b)
# subtraction
print ('Subtraction: ', a - b)
# multiplication
print ('Multiplication: ', a * b)
# division
print ('Division: ', a / b)
# floor division
print ('Floor Division: ', a // b)
# modulo
print ('Modulo: ', a % b)
# a to the power b
print ('Power: ', a ** b)
Output
Sum: 9
Subtraction: 5
Multiplication: 14
Division: 3.5
Floor Division: 3
Modulo: 1
Power: 49
+ to add a and b
- to subtract b from a
* to multiply a and b
/ to divide a by b
// to floor divide a by b
# assign 5 to x
x = 5
= Assignment Operator a = 7
a += 1 # a = a +
+= Addition Assignment
1
a -= 3 # a = a -
-= Subtraction Assignment
3
a *= 4 # a = a *
*= Multiplication Assignment
4
a /= 3 # a = a /
/= Division Assignment
3
a %= 10 # a = a
%= Remainder Assignment
% 10
a **= 10 # a = a
**= Exponent Assignment
** 10
Example 2: Assignment Operators
# assign 10 to a
a = 10
# assign 5 to b
b = 5
print(a)
# Output: 15
Run Code
# equal to operator
print('a == b =', a == b)
Output
a == b = False
a != b = True
a > b = True
a < b = False
a >= b = True
a <= b = False
Note: Comparison operators are used in decision-making
and loops. We'll discuss more of the comparison operator
and decision-making in later tutorials.
Logical AND:
and a and b
True only if both the operands are True
Logical OR:
or a or b
True if at least one of the operands is True
Logical NOT:
not not a
True if the operand is False and vice-versa.
# logical OR
print(True or False) # True
# logical NOT
print(not True) # False
Run Code
In Python, is and is not are used to check if two values are located on the same part of the
memory. Two variables that are equal does not imply that they are identical.
Membership operators
Operator Meaning
Output
True
True
True
False