Programming Fundamentals
Operators
1994. Intel ships the Pentium CPU with a hardware bug in the division unit. The expression 4195835.0 / 3145727.0 returns 1.333739068 instead of 1.333820449. Nobody caught it for six months. The recall cost Intel $475 million. One wrong division operator at the silicon level - and a company is in crisis.
- **Games**: damage = base_attack * critical_multiplier - arithmetic determines game balance
- **E-commerce**: total = price * quantity - discount - every symbol moves money
- **Security**: can_access = is_authenticated and not is_banned - logic opens and closes doors
- **Navigation**: is_nearby = distance < 100 and traffic_level == 'low' - comparisons change routes
Historical context
In 1957, IBM's team under John Backus shipped Fortran - the first language with mathematical operators in human-readable form. Before that, programmers expressed operations in machine codes. Backus insisted that A = B + C look like a formula, not a hex sequence. The Fortran compiler generated code so efficient that skeptics refused to believe it - no human wrote assembly that tight. That operator syntax has survived into Python, JavaScript, and every modern language.
Цели урока
- Master arithmetic operators (+, -, *, /, //, %, **)
- Understand comparison operators (==, !=, <, >, <=, >=)
- Use logical operators (and, or, not)
- Know operator precedence
Предварительные знания
- Variables and data types (int, float, str, bool)
- Assignment via = (lesson 3)
Arithmetic Operators
Python ships seven arithmetic operators that cover all practical math needs.
| Operator | Name | Example | Result |
|---|---|---|---|
| + | Addition | 5 + 3 | 8 |
| - | Subtraction | 5 - 3 | 2 |
| * | Multiplication | 5 * 3 | 15 |
| / | Division | 7 / 2 | 3.5 |
| // | Floor division | 7 // 2 | 3 |
| % | Remainder (modulo) | 7 % 2 | 1 |
| ** | Exponentiation | 2 ** 3 | 8 |
Division: / vs //
What is the actual difference?
```python print(7 / 2) # 3.5 - true division (float) print(7 // 2) # 3 - floor division (int, discards fraction) print(7 % 2) # 1 - remainder # Practical: convert minutes to hours and minutes total_minutes = 135 hours = total_minutes // 60 # 2 minutes = total_minutes % 60 # 15 print(f"{hours}h {minutes}min") # 2h 15min ```
The % operator is a workhorse: check parity (n % 2 == 0), extract the last digit (n % 10), wrap an array index around the end (i % length).
What does print(17 % 5) output?
Comparison Operators
Comparisons return True or False. They are the foundation of every conditional and loop in the language.
| Operator | Meaning | Example | Result |
|---|---|---|---|
| == | Equal to | 5 == 5 | True |
| != | Not equal to | 5 != 3 | True |
| < | Less than | 3 < 5 | True |
| > | Greater than | 3 > 5 | False |
| <= | Less than or equal | 5 <= 5 | True |
| >= | Greater than or equal | 3 >= 5 | False |
== vs =: a single = assigns (stores a value). A double == compares (tests equality). Mixing them up is the most common beginner bug.
Comparisons in action
Practical examples
```python age = 18 print(age >= 18) # True - of legal age print(age == 21) # False password = "secret123" print(password == "secret123") # True print(password == "Secret123") # False - case sensitive! # Chained comparisons (Python feature) x = 5 print(1 < x < 10) # True - x is between 1 and 10 ```
What does print(x == "5") output when x = 5?
Logical Operators
Logical operators combine multiple conditions into a single boolean expression.
| Operator | Meaning | Example | Result |
|---|---|---|---|
| and | AND (both must be True) | True and True | True |
| or | OR (at least one True) | True or False | True |
| not | NOT (invert) | not True | False |
Combining conditions
Real-world scenarios
```python age = 25 has_license = True # Car rental: age >= 21 AND has a license can_rent = age >= 21 and has_license print(can_rent) # True # Discount: student OR senior is_student = False is_senior = True has_discount = is_student or is_senior print(has_discount) # True # Not banned is_banned = False can_post = not is_banned print(can_post) # True ```
Short-circuit evaluation: Python stops evaluating as soon as the result is known. In False and X, Python skips X entirely. In True or X, Python skips X. This prevents errors when X has side effects.
Writing: if x == 1 or 2 or 3
Must write: if x == 1 or x == 2 or x == 3 (or better: if x in [1, 2, 3])
or 2 is always True (any nonzero number is truthy). Python reads the original as (x == 1) or (2) or (3), and 2 and 3 are truthy - the condition fires regardless of x.
What does print(True or False and False) output?
Compound Assignment Operators
Instead of x = x + 5 write x += 5. Shorter and unambiguous.
| Operator | Equivalent | Example |
|---|---|---|
| += | x = x + n | x += 5 |
| -= | x = x - n | x -= 3 |
| *= | x = x * n | x *= 2 |
| /= | x = x / n | x /= 4 |
| //= | x = x // n | x //= 3 |
| %= | x = x % n | x %= 7 |
| **= | x = x ** n | x **= 2 |
Compound operators in action
Typical game score scenarios
```python score = 0 score += 10 # earned 10 points -> score = 10 score += 5 # 5 more -> score = 15 score *= 2 # double! -> score = 30 lives = 3 lives -= 1 # lost a life -> lives = 2 print(f"Score: {score}, Lives: {lives}") ```
What is x after: x = 10; x //= 3; x += 1?
Operator Precedence
Operators execute in a fixed priority order. Multiplication fires before addition - same as in math.
Evaluation order
Highest to lowest precedence
**Precedence (highest to lowest):** 1. `**` - exponentiation 2. `*, /, //, %` - multiplication and division 3. `+, -` - addition and subtraction 4. `==, !=, <, >, <=, >=` - comparisons 5. `not` - logical NOT 6. `and` - logical AND 7. `or` - logical OR
When in doubt, use parentheses. (2 + 3) * 4 unambiguously gives 20. Parentheses eliminate ambiguity and prevent bugs.
What does print(2 + 3 * 4 ** 2) output?
Where this lesson sits in the curriculum
Operators are the tools that turn variables into computations. The next lessons assemble them into logic and program flow:
- Strings — Concatenation + and repetition * on strings are the same operators applied to text
- Conditionals — Comparisons ==, <, >= are the fuel for if/elif/else
- Loops — while and for hang on conditions built with and, or, not
- Functions — Logical expressions become guard clauses at the top of functions
Key Takeaways
- **Arithmetic**: +, -, *, /, //, %, ** - seven operators cover all practical math
- **// and %**: floor division and remainder, a capable pair for time and space problems
- **Comparisons**: ==, !=, <, >, <=, >= - return bool, the basis of all logic
- **Logic**: and (AND), or (OR), not (NOT) - Boolean algebra in one line
- **Compound**: +=, -= and friends, the industry-standard shorthand
- **Precedence**: ** > */% > +- > comparisons > not > and > or
Вопросы для размышления
- The Intel Pentium bug went undetected for six months. What does that say about testing edge cases in arithmetic?
- When should // be used instead of / and why is that an architectural decision, not just a syntax choice?
- Why is short-circuit evaluation in and/or not just a convenience but a defensive programming mechanism?
Связанные уроки
- prog-03-variables — Without understanding types, operator results are unpredictable (5 == '5' is False)
- prog-05-strings — String concatenation and slicing extend the same operator concepts
- prog-06-conditionals — Comparison and logical operators are the raw material for if/else
- prog-07-loops — Loop conditions rely on comparison and logical operators
- prog-09-recursion — Compound operators like += are the foundation of the accumulator pattern used in recursion
- alg-01-big-o