Operators (Arithmetic / Comparison / Logical)
Python's operators fall into three basic categories: arithmetic, comparison, and logical. Python has unique syntax not found in other languages, such as chaining comparison operators to write 1 < x < 10 in a single expression.
Syntax
# Arithmetic operators result = left + right # addition result = left - right # subtraction result = left * right # multiplication result = left / right # division (always returns float) result = left // right # floor division (returns int) result = left % right # modulo (remainder) result = left ** right # exponentiation # Comparison operators (result is True or False) left == right # equal left != right # not equal left > right # greater than left >= right # greater than or equal left < right # less than left <= right # less than or equal left is right # same object left is not right # different objects value in sequence # contained in value not in sequence # not contained in # Chained comparison (Python-specific) lower <= value <= upper # range check in one line # Logical operators condition_a and condition_b # True when both are true condition_a or condition_b # True when either is true not condition # invert the truth value
Arithmetic Operators
| Operator | Name | Notes |
|---|---|---|
| + | Addition | Returns the sum of left and right. Acts as concatenation for strings and lists. |
| - | Subtraction | Returns left minus right. |
| * | Multiplication | Returns the product of left and right. Acts as repetition for strings and lists. |
| / | Division | Returns left divided by right. Always returns float, even for two integers. |
| // | Floor division | Returns the result of division rounded down (floor). For negative numbers, rounds toward negative infinity, not toward zero. |
| % | Modulo | Returns the remainder of left divided by right. |
| ** | Exponentiation | Returns left raised to the power of right. Equivalent to pow(x, y). |
Comparison Operators
| Operator | Name | Notes |
|---|---|---|
| == | Equal | Returns True when the values of left and right are equal. |
| != | Not equal | Returns True when the values of left and right differ. |
| > | Greater than | Returns True when left is greater than right. |
| >= | Greater than or equal | Returns True when left is greater than or equal to right. |
| < | Less than | Returns True when left is less than right. |
| <= | Less than or equal | Returns True when left is less than or equal to right. |
| is | Identity | Returns True when left and right are the same object. Use == for value equality comparisons. |
| is not | Non-identity | Returns True when left and right are different objects. |
| in | Containment | Returns True when a value is contained in a sequence (list, string, dict, etc.). |
| not in | Non-containment | Returns True when a value is not contained in a sequence. |
Logical Operators
| Operator | Notes |
|---|---|
| and | Returns the left operand if it is falsy; otherwise returns the right. The overall result is True when both sides are true. |
| or | Returns the left operand if it is truthy; otherwise returns the right. The overall result is True when either side is true. |
| not | Inverts the truth value of the operand and returns True or False. |
Sample Code
Basic usage of arithmetic operators. Pay attention to the difference between / and //.
arithmetic.py
# Use Dragon Ball character power levels to demonstrate arithmetic operators. goku_power = 9000 vegeta_power = 8000 print(goku_power + vegeta_power) # 17000 (addition) print(goku_power - vegeta_power) # 1000 (subtraction) print(goku_power * 2) # 18000 (multiplication) # / (division) always returns float, even for two integers. print(goku_power / vegeta_power) # 1.125 # // (floor division) truncates the decimal part. print(goku_power // vegeta_power) # 1 # % (modulo) checks divisibility. total_fighters = 23 team_size = 3 print(total_fighters % team_size) # 2 (not divisible by 3) print(total_fighters // team_size) # 7 (number of full teams) # ** (exponentiation) computes Super Saiyan power multiplier. base_power = 1000 multiplier = 50 super_power = base_power * (multiplier ** 2) print(super_power) # 2500000
Running the code produces the following output:
python3 arithmetic.py 17000 1000 18000 1.125 1 2 7 2500000
Basic usage of comparison operators, and the difference between == and is.
comparison.py
# Compare Dragon Ball character power levels.
goku_power = 9000
frieza_power = 120000
# Use == and != to compare values.
print(goku_power == frieza_power) # False
print(goku_power != frieza_power) # True
# Use > / >= / < / <= for magnitude comparisons.
print(frieza_power > goku_power) # True
print(goku_power >= 9000) # True
print(goku_power < frieza_power) # True
# The difference between is and ==.
# == compares values; is checks whether they are the same object.
name_a = "Goku"
name_b = "Goku"
print(name_a == name_b) # True (values are equal)
print(name_a is name_b) # True (short strings are often reused by Python)
# PEP 8 recommends is for None comparisons.
hidden_power = None
print(hidden_power is None) # True (recommended)
print(hidden_power == None) # True (works but not preferred)
# Use in / not in to check list membership.
z_fighters = ["Goku", "Vegeta", "Piccolo", "Krillin", "Trunks"]
print("Goku" in z_fighters) # True
print("Frieza" not in z_fighters) # True
Running the code produces the following output:
python3 comparison.py False True True True True True True True True True
Python-specific chained comparisons. Multiple comparisons can be written consecutively.
chained_comparison.py
# In Python, comparison operators can be chained for range checks in one line.
# In other languages you would write "x >= 1000 and x <= 9000".
goku_power = 5000
# Check whether a value falls within a range in one line.
if 1000 <= goku_power <= 9000:
print("Normal warrior level")
# Three or more comparisons can be chained.
a, b, c = 100, 200, 300
print(a < b < c) # True (100 < 200 and 200 < 300)
print(a < b > c) # False (100 < 200 is True but 200 > 300 is False)
# Determine rank based on power level.
def check_rank(power):
if power < 1000:
return "Civilian"
elif 1000 <= power < 10000:
return "Warrior"
elif 10000 <= power < 100000:
return "Elite Warrior"
else:
return "Divine Level"
print(check_rank(530)) # Civilian
print(check_rank(8500)) # Warrior
print(check_rank(53000)) # Elite Warrior
print(check_rank(150000)) # Divine Level
Running the code produces the following output:
python3 chained_comparison.py Normal warrior level True False Civilian Warrior Elite Warrior Divine Level
Logical operator behavior. and / or use short-circuit evaluation.
logical.py
# Use logical operators to determine eligibility for a Dragon Ball tournament.
name = "Vegeta"
power = 8000
is_registered = True
# and: True when both sides are True.
if power >= 5000 and is_registered:
print(name, "can enter the World Martial Arts Tournament")
# or: True when either side is True.
is_saiyan = True
is_namekian = False
if is_saiyan or is_namekian:
print(name, "is an alien")
# not: inverts the truth value.
is_villain = False
if not is_villain:
print(name, "is currently not a villain")
# Short-circuit evaluation behavior.
# and: right side is not evaluated if left is falsy.
# or: right side is not evaluated if left is truthy.
# Default value pattern using or
nickname = ""
display_name = nickname or name # nickname is empty (falsy), so name is used.
print("Display name:", display_name) # Vegeta
# Safe access pattern using and
stats = {"power": 8000, "speed": 7500}
label = "power" in stats and stats["power"]
print("Power:", label) # 8000
Running the code produces the following output:
python3 logical.py Vegeta can enter the World Martial Arts Tournament Vegeta is an alien Vegeta is currently not a villain Display name: Vegeta Power: 8000
Compound assignment operators (+=, -= etc.) and operator precedence.
compound_precedence.py
# Compound assignment operators are used frequently. power = 1000 power += 500 # power = power + 500 print(power) # 1500 power *= 3 # power = power * 3 print(power) # 4500 power //= 2 # power = power // 2 print(power) # 2250 power **= 2 # power = power ** 2 print(power) # 5062500 # Operator precedence: ** is highest; logical operators are lowest. # Using parentheses to make intent clear improves readability. result = 2 + 3 * 4 # 14 (* is calculated before +) result2 = (2 + 3) * 4 # 20 (parenthesized expression first) print(result, result2) # Comparison operators have lower precedence than arithmetic operators. # The following two lines mean the same thing. print(3 + 2 >= 5) # True (5 >= 5) print((3 + 2) >= 5) # True (parentheses make intent explicit)
Running the code produces the following output:
python3 compound_precedence.py 1500 4500 2250 5062500 14 20 True True
Common Mistakes
Common Mistake 1: Confusing / and //
/ is floating-point division and always returns float, even when dividing two integers. // is floor division and returns an integer. Not being clear about which one to use can let an unintended float slip into a calculation.
ng_division.py
goku_power = 9000 vegeta_power = 8000 # Wrong: expecting an integer quotient but / returns float ratio = goku_power / vegeta_power print(ratio) # 1.125 (float is returned) print(type(ratio)) # <class 'float'> # Using / for index or count calculations can cause errors. total = 23 team_size = 3 teams = total / team_size # 7.666... # range(teams) causes an error (range cannot accept float)
Running the code produces the following output:
python3 ng_division.py 1.125 <class 'float'>
ok_division.py
total = 23
team_size = 3
# Use // when an integer quotient is needed.
teams = total // team_size
remainder = total % team_size
print("Teams:", teams) # 7
print("Remainder:", remainder) # 2
# Can be passed to range().
for i in range(teams):
print("Team", i + 1)
Running the code produces the following output:
python3 ok_division.py Teams: 7 Remainder: 2 Team 1 Team 2 Team 3 Team 4 Team 5 Team 6 Team 7
Common Mistake 2: Using == to compare floating-point numbers
Floating-point numbers are approximated in binary, so calculation results can differ slightly. 0.1 + 0.2 is not exactly 0.3, so comparing with == returns False.
ng_float_compare.py
# Wrong: using == to compare floating-point numbers result = 0.1 + 0.2 print(result) # 0.30000000000000004 print(result == 0.3) # False (not what was intended)
Running the code produces the following output:
python3 ng_float_compare.py 0.30000000000000004 False
ok_float_compare.py
import math result = 0.1 + 0.2 # Compare using a tolerance (epsilon). print(abs(result - 0.3) < 1e-9) # True # You can also use math.isclose(). print(math.isclose(result, 0.3)) # True # Converting to int before comparing also works in some cases. goku_power = 9000.0 print(int(goku_power) == 9000) # True
Running the code produces the following output:
python3 ok_float_compare.py True True True
Common Mistake 3: Operator precedence errors
* has higher precedence than +, so 2 + 3 * 4 evaluates as 2 + (3 * 4) = 14, not (2 + 3) * 4 = 20. Use parentheses to make the intended order explicit.
ng_precedence.py
base_power = 1000 multiplier = 2 bonus = 500 # The precedence may not match your expectation. result = base_power + multiplier * bonus # 1000 + (2 * 500) = 2000 (intent is ambiguous) print(result) # 2000 # If the intent is (base_power + multiplier) * bonus: intended = (base_power + multiplier) * bonus # (1000 + 2) * 500 = 501000 print(intended) # 501000
Running the code produces the following output:
python3 ng_precedence.py 2000 501000
ok_precedence.py
base_power = 1000 multiplier = 2 bonus = 500 # Use parentheses to make intent explicit. result = base_power + (multiplier * bonus) # written explicitly print(result) # 2000 result2 = (base_power + multiplier) * bonus print(result2) # 501000 # ** is right-associative and has the highest precedence. print(2 ** 3 ** 2) # 512 (2 ** (3 ** 2) = 2 ** 9) print((2 ** 3) ** 2) # 64
Running the code produces the following output:
python3 ok_precedence.py 2000 501000 512 64
Notes
The most important thing to watch for among Python's arithmetic operators is the difference between / and //. / always returns float, even for two integers (e.g. 7 / 2 is 3.5). Use // when you want an integer quotient. Note that // rounds toward negative infinity for negative numbers (e.g. -7 // 2 is -4).
The distinction between == and is matters. Use == for value equality comparisons; reserve is for None comparisons and same-object checks. Short strings and small integers may cause is to return True because Python caches them internally, but that is an implementation detail and is not guaranteed.
and / or return one of their operands as-is rather than returning True or False. For example, "" or "default" returns "default". This short-circuit evaluation behavior can be used to set default values or write safe access patterns. For complex expressions, using parentheses to express precedence explicitly improves readability.
If you find any errors or copyright issues, please contact us.