= 9
a = 2
b print('Subtraction:', a - b)
print('Division:', a / b)
print('Floor Division:', a // b)
print('Modulo:', a % b)
print('Power:', a ** b)
Subtraction: 7
Division: 4.5
Floor Division: 4
Modulo: 1
Power: 81
Operators are essential for performing various operations on variables and values. You may want to multiply two numbers or compare them to know which one is greater, and operators allow us to do it.
Arithmetic operators can be used with numerical variables such as int
and float
.
Description | Operator | Example |
---|---|---|
Addition | + | a + b |
Subtraction | - | a - b |
Multiplication | * | a * b |
Division | / | a / b |
Floor Division | // | a // b |
Modulo | % | a % b |
Exponentiation | ** | a ** b |
= 9
a = 2
b print('Subtraction:', a - b)
print('Division:', a / b)
print('Floor Division:', a // b)
print('Modulo:', a % b)
print('Power:', a ** b)
Subtraction: 7
Division: 4.5
Floor Division: 4
Modulo: 1
Power: 81
We can compare two variables (or a variable and a value) using comparison operators. They are applicable to numerical variables, strings and booleans.
Description | Operator | Example |
---|---|---|
Equal To | == | a == b |
Not Equal To | != | a != b |
Greater Than | > | a > b |
Less Than | < | a < b |
Greater Than or Equal To | >= | a >= b |
Less Than or Equal To | <= | a <= b |
= 5
a = 2
b print("Equal To:", a == b)
print("Less Than:", a > b)
print("Not Equal To:", a != b)
print("Greater Than:", a < b)
Equal To: False
Less Than: True
Not Equal To: True
Greater Than: False
Logical operators are used to combine conditional statements or negate them, and can only be applied to booleans.
Description | Operator | Example |
---|---|---|
Logical AND | and | (a == b) and (a > c) |
Logical OR | or | (a > b) or (a < c) |
Logical NOT | not | not (a > b) |
= 5
a = 2
b = 4
c print("(a == b) and (a > c)", (a == b) and (a > c))
print("(a > b) or (a < c)", (a > b) or (a < c))
print("not (a > b):", not (a > b))
(a == b) and (a > c) False
(a > b) or (a < c) True
not (a > b): False