Python Operators: Arithmetic, Comparison, Logical and More - Python with AI tutorial chapter 12
Python

Python Operators: Arithmetic, Comparison, Logical and More

Python with AI Tutorial · Chapter 12 of 48

Python operators are the symbols that combine values into expressions: + to add, == to compare, and to join conditions, in to test membership. This chapter walks through every operator group in Python, from arithmetic to bitwise, and finishes with the precedence rules that decide which part of an expression runs first.

Arithmetic operators

The arithmetic operators work on ints and floats. Two of them trip up newcomers: / always returns a float, while // floors the result to a whole number, and % gives the remainder.

price = 250
qty = 7

print(price + qty)    # addition
print(price - qty)    # subtraction
print(price * qty)    # multiplication
print(price / qty)    # true division
print(price // qty)   # floor division
print(price % qty)    # modulus (remainder)
print(2 ** 10)        # exponent
Output:
257
243
1750
35.714285714285715
35
5
1024

The modulus operator is more useful than it looks. row % 2 == 0 picks even rows for striped tables, minutes % 60 gives the leftover minutes after whole hours, and index % len(items) wraps a counter back to zero.

Floor division and modulus behave consistently with negative numbers, but not in the way a calculator does. Python rounds toward negative infinity, so -17 // 5 is -4 and -17 % 5 is 3; the two results always satisfy a == (a // b) * b + a % b. If you need the remainder to carry the sign of the dividend, as in C or Excel’s MOD-adjacent functions, use math.fmod() instead.

Operators on strings and lists

Several operators are overloaded, meaning they do something sensible for non-numeric types too. + joins two strings or two lists, * repeats them, and comparison operators compare strings alphabetically and lists item by item. This is why "10" + "20" gives "1020" rather than 30, one of the first surprises in the casting chapter.

q1 = ["Jan", "Feb", "Mar"]
q2 = ["Apr", "May", "Jun"]
print(q1 + q2)
print("=" * 12)
print("10" + "20")
print([0] * 4)
print([1, 2, 3] < [1, 2, 4])
Output:
['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
============
1020
[0, 0, 0, 0]
True

Mixing types that do not understand each other, such as a string plus an integer, raises TypeError. Python never guesses which one you meant to convert.

Assignment operators

Every arithmetic operator has a shorthand that updates a variable in place. balance += 250 means balance = balance + 250. They keep running totals short and readable.

balance = 1000
balance += 250
print(balance)
balance -= 100
print(balance)
balance *= 2
print(balance)
balance //= 7
print(balance)
balance %= 100
print(balance)
Output:
1250
1150
2300
328
28

Comparison operators

Comparisons return a boolean. They work on numbers, strings (compared alphabetically by character code) and most other types, and Python lets you chain them, so 1 < x < 10 reads like the maths you learned at school.

Chaining is more than a shortcut. low <= value <= high evaluates value only once and is clearer than the equivalent low <= value and value <= high, which is why you will see it in range checks and validation code throughout the course.

target = 50000
actual = 52500

print(actual > target)
print(actual == target)
print(actual != target)
print(actual >= 52500)
print("apple" < "banana")
print(1 < actual < 60000)
Output:
True
False
True
True
True
True

Logical operators

and, or and not combine conditions. They short-circuit, meaning Python stops as soon as the result is certain, and they return one of the original operands rather than always returning a bare True or False.

age = 34
years_service = 6

print(age > 30 and years_service >= 5)
print(age > 40 or years_service >= 5)
print(not age > 30)
print("" or "default")
print(0 and 5)
Output:
True
True
False
default
0

The last two lines show the operand-returning behaviour. "" or "default" returns the first truthy value, a common idiom for fallbacks, while 0 and 5 stops at the falsy 0 and returns it.

Try it with AI

Ask the assistant to predict outputs for tricky expressions and to explain the operand-returning behaviour of and/or.

I am learning Python operators. For each expression below, tell me the result and explain it in one sentence: 17 // 5, -17 // 5, 17 % 5, -17 % 5, 2 ** 3 ** 2, -2 ** 2, "" or 0 or "x", 3 and 0 and 5, not 0 == False, 5 > 3 > 1. Then give me five new expressions of the same kind to solve myself, with the answers hidden at the bottom.

Identity and membership operators

in and not in test whether a value appears in a string, list, tuple, set or dictionary. is and is not test whether two names refer to the very same object in memory, which is different from having equal contents.

regions = ["North", "South", "East"]
print("East" in regions)
print("West" not in regions)

a = [1, 2]
b = [1, 2]
c = a
print(a == b, a is b, a is c)
print(None is None)
Output:
True
True
True False True
True
Common mistake: using is to compare values. a is b is False above even though both lists hold [1, 2], because they are two separate objects. Use == for values and reserve is for None, True and False, as in if result is None:.

Bitwise operators

Bitwise operators work on the individual binary digits of integers. You will meet them when handling permission flags, hardware registers or compact settings, and in pandas, where & and | combine filter conditions.

read = 0b100     # 4
write = 0b010    # 2

perms = read | write
print(perms)
print(perms & write)
print(perms ^ read)
print(1 << 3)
print(bin(perms))
Output:
6
2
2
8
0b110

Operator precedence

When an expression mixes operators, Python applies them in a fixed order. Multiplication beats addition, exponent beats both, and not beats and, which beats or. Parentheses always win, so use them whenever the order is not obvious.

Priority Operators Notes
1 (highest) () Parentheses and function calls
2 ** Exponent, evaluated right to left
3 +x, -x, ~x Unary plus, minus, bitwise not
4 *, /, //, % Multiplication and division family
5 +, - Addition and subtraction
6 <<, >> Bit shifts
7 & Bitwise and
8 ^ Bitwise xor
9 | Bitwise or
10 ==, !=, <, <=, >, >=, is, in All comparisons, chainable
11 not Logical not
12 and Logical and
13 or Logical or
14 x if c else y Conditional expression
15 (lowest) := Assignment expression (walrus)
print(2 + 3 * 4)
print((2 + 3) * 4)
print(-3 ** 2)
print((-3) ** 2)
print(10 - 4 - 3)
print(2 ** 3 ** 2)
print(not True or True)
Output:
14
20
-9
9
3
512
True

Two results deserve a second look. -3 ** 2 is -9 because the exponent is applied before the unary minus, and 2 ** 3 ** 2 is 2 ** 9, not 8 ** 2, because exponents group from the right.

Conditional expressions and the walrus operator

Two compact operators round out the set. The conditional expression x if condition else y chooses between two values on one line, and the walrus operator := (Python 3.8+) assigns a value in the middle of an expression so you can test it and reuse it without a separate line.

sales = [1200, 980, 1500]

if (n := len(sales)) > 2:
    print(f"{n} sales records")

status = "Bonus" if sum(sales) > 3000 else "No bonus"
print(status)
Output:
3 sales records
Bonus
Try it with AI

Paste a long condition from your own code and ask the assistant to add parentheses that make the precedence explicit, without changing the result.

Here is a Python condition: if not status == "paid" or amount > 1000 and region in ("North", "East") or overdue_days // 30 >= 1: . First tell me exactly how Python groups it according to operator precedence by adding parentheses that do not change the meaning. Then tell me whether that grouping matches what a human would probably intend, and rewrite it in a clearer form if not.

Common mistakes

  • Expecting / to return an integer. 10 / 2 is 5.0; use // when you need 5.
  • Assuming // and % round toward zero. Python floors, so -7 // 2 is -4 and -7 % 2 is 1.
  • Writing -3 ** 2 and expecting 9. Wrap the base in parentheses.
  • Using is instead of == to compare numbers or strings. It may seem to work for small values and then fail unpredictably.
  • Comparing floats for exact equality. 0.1 + 0.2 == 0.3 is False; use math.isclose() or round first.

Exercise

A customer orders 4 units at 249.99 each. Orders of 3 or more units get a 10% discount, and 18% tax is added to the discounted amount. Using arithmetic, comparison and a conditional expression, print the subtotal, the net amount after discount and the final total, each to two decimal places.

Show answer
unit_price = 249.99
qty = 4

subtotal = unit_price * qty
discount = 0.10 if qty >= 3 else 0
net = subtotal * (1 - discount)
total = net * 1.18

print(f"Subtotal: {subtotal:.2f}")
print(f"Net after discount: {net:.2f}")
print(f"Total with tax: {total:.2f}")
Output:
Subtotal: 999.96
Net after discount: 899.96
Total with tax: 1061.96

The parentheses around 1 - discount are required; without them the multiplication would happen first and the discount would be subtracted from the product.

Related chapters

FAQ

What is the difference between / and // in Python?

The single slash performs true division and always returns a float, so 7 / 2 is 3.5. The double slash performs floor division and returns the largest whole number not greater than the result, so 7 // 2 is 3 and -7 // 2 is -4.

What does the % operator do in Python?

It returns the remainder after division. 17 % 5 is 2 because 5 fits into 17 three times with 2 left over. It is commonly used to test for even numbers, wrap counters and split minutes from hours.

What is the difference between == and is?

== compares values and is True when two objects hold equal contents. is compares identity and is True only when both names point to the same object in memory. Use == for data and is only for None, True and False.

Working with spreadsheets too? Ready-made Excel, Google Sheets and Power BI templates are at NextGenTemplates.com.

Chapter 12 of 48 · Python with AI: all 48 chapters

PK
Meet PK, the founder of NeotechNavigators.com! With over 15 years of experience in Data Visualization, Excel Automation, and dashboard creation. PK is a Microsoft Certified Professional who has a passion for all things in Excel. PK loves to explore new and innovative ways to use Excel and is always eager to share his knowledge with others. With an eye for detail and a commitment to excellence, PK has become a go-to expert in the world of Excel. Whether you're looking to create stunning visualizations or streamline your workflow with automation, PK has the skills and expertise to help you succeed. Join the many satisfied clients who have benefited from PK's services and see how he can take your data analysis skills to the next level!
https://neotechnavigators.com