Operators Checkpoint
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Test your grip on Python operators, precedence and short-circuiting before moving on to input and output.
Operator precedence hierarchy
Operator precedence is the fixed order in which Python applies operators. Brackets come first, then **, then * / // %, then + -, then comparisons, then not, and, or.
When an expression has many operators, Python needs a fixed order. Learn it, and use brackets when in doubt.
result = 10 + 2 * 3 ** 2print(result)print(-2 ** 2)print(2 ** 3 ** 2)print(10 - 4 - 3)Example 1 · Discount rule
cart_total = 1200has_coupon = Trueis_member = False
qualifies_discount = (cart_total >= 1000 and has_coupon) or is_memberprint(qualifies_discount)True
What this code does
cart_total >= 1000isTrue.True and has_couponisTrue.True or is_memberisTrue, so the customer qualifies.
Example 2 · Hours and minutes
total_minutes = 135hours = total_minutes // 60minutes = total_minutes % 60
print(hours, minutes)print(0 <= minutes < 60)2 15 True
What this code does
//gives the whole hours and%the minutes left.- A chained check confirms the minutes stay below 60.
Order: 3 ** 2 = 9, then 2 * 9 = 18, then 10 + 18 = 28. ** goes right to left, so 2 ** 3 ** 2 is 2 ** 9. - goes left to right, so 10 - 4 - 3 is 3.
Bitwise versus logical operators
Do not mix up and / or with & / |. The words work on truth values; the symbols work on the bits of integers.
print(5 & 3)print(5 and 3)Example 3 · Safe average
total = 500units = 0check = units > 0 and total / units > 100print(check)
units = 4check = units > 0 and total / units > 100print(check)False True
What this code does
- With
units = 0the guard isFalse, so the division is skipped. - With
units = 4the average 125.0 is above 100.
5 & 3 compares bits: 0101 & 0011 = 0001, which is 1. 5 and 3 asks about truth: 5 is true, so it returns the right-hand value, 3.
Finish up
Mark complete & continue
Next: Printing with sep and end