ASAmol Shukla
Projects
Courses
Prompts
Skills
Contact
Resume
Course Outline
Syllabus Overview

Complete Python Course: From Zero to Professional

Courses/Complete Python Course: From Zero to Professional/Lesson 4: Operators & Expressions
35 mins lesson duration•7 mins read

Lesson 4: Operators & Expressions

Arithmetic, comparison, logical, and assignment operators — plus expression evaluation order.

What are Operators?

Operators are the verbs of programming — they tell Python what to do with values. You already use them in math class; Python just gives them superpowers like integer division and modulo. An expression is any combination of values and operators that Python can evaluate to a single result.

What You'll Learn in This Lesson

  • Use arithmetic, comparison, and logical operators
  • Understand operator precedence (order of operations)
  • Use assignment shortcuts like +=
  • Split numbers into digits with // and %
  • Understand the difference between = and ==

Arithmetic Operators

Operator Meaning Example Result
+ Addition 7 + 3 10
- Subtraction 7 - 3 4
* Multiplication 7 * 3 21
/ Division (always float) 7 / 2 3.5
// Floor division (integer) 7 // 2 3
% Modulo (remainder) 7 % 2 1
** Power 2 ** 3 8

Two operators deserve special attention:

  • // floor division drops the decimal part: 17 // 5 is 3 (not 3.4).
  • % modulo returns the remainder: 17 % 5 is 2, because 17 = 3*5 + 2.

Pizza visualization for modulo: 17 slices ÷ 5 friends = 3 full slices each, and 2 slices left over. The // gives you 3, the % gives you 2.

+ and * also work on other types:

print("Py" + "thon")      # 'Python' — concatenation
print("ha" * 3)           # 'hahaha' — repetition
print([1, 2] + [3, 4])    # [1, 2, 3, 4] — list concatenation (Lesson 8)

This is called operator overloading — the same symbol means different things depending on the type. It is convenient but a common source of surprises: "5" + 5 raises TypeError because a string and an int don't mix.


Comparison Operators

Comparisons always return a boolean — True or False:

Operator Meaning Example
== Equal to 5 == 5 → True
!= Not equal 5 != 4 → True
> Greater than 5 > 4 → True
< Less than 5 < 4 → False
>= Greater or equal 5 >= 5 → True
<= Less or equal 4 <= 5 → True

Never confuse = (assignment) with == (comparison). A single = stores a value; a double == asks a question.

Comparisons chain naturally in Python:

age = 25
print(18 <= age < 60)   # True — chained comparison, one expression

That single line is equivalent to 18 <= age and age < 60 — Python lets you write the math-style version directly.


Logical Operators

Logical operators combine booleans:

Operator Rule Example
and Both sides True True and False → False
or At least one side True True or False → True
not Flips True ↔ False not True → False
A B A and B A or B not A
True True True True False
True False False True False
False True False True True
False False False False True

These let you write real-world rules: "Can enter if age ≥ 18 and has ID".

Short-circuiting is a powerful side effect: Python evaluates and/or left to right and stops as soon as the answer is decided. In a and b, if a is falsy, b never runs. In a or b, if a is truthy, b never runs. This is used to write safe one-liners:

# Only divide if denominator is non-zero
result = x / y if y != 0 else 0

Precedence — Order of Operations

Python follows standard math rules. From highest to lowest priority:

  1. Parentheses ( )
  2. Exponents **
  3. *, /, //, % (left to right)
  4. +, - (left to right)
  5. Comparisons (==, >, ...)
  6. not, then and, then or
  7. Assignment =
print(3 + 4 * 2)      # 11  (multiplication first)
print((3 + 4) * 2)    # 14  (parentheses override)
print(2 ** 3 ** 2)    # 512 — ** binds right-to-left: 2 ** (3 ** 2)

Rule of thumb: when in doubt, add parentheses. Clarity beats cleverness every time.


Assignment Shortcuts

x += 5 is shorthand for x = x + 5. The shortcut works with most operators:

Shortcut Equivalent
x += 5 x = x + 5
x -= 5 x = x - 5
x *= 5 x = x * 5
x /= 5 x = x / 5
x //= 5 x = x // 5
x %= 5 x = x % 5
x **= 2 x = x ** 2

These keep counters, totals, and accumulators compact — you will use += on almost every loop you write.


Real-World Uses of // and %

  • Time math: total_minutes = 130 → hours = 130 // 60 (2), mins = 130 % 60 (10).
  • Even/odd checks: n % 2 == 0 means even.
  • Splitting digits: 123 % 10 → 3; 123 // 10 → 12.
  • Cycling/wrapping: index % len(items) wraps an index around a list forever.
  • Coin/cash change: divide by the largest denomination with //, keep the remainder with %.

Common Mistakes to Avoid

  • Mistake: Using = inside an if condition — Fix: always use == for comparison.
  • Mistake: Expecting 7 / 2 to give 3 — Fix: / always gives a float (3.5); use // for integer division.
  • Mistake: Forgetting that and binds tighter than or — Fix: add parentheses to make the logic explicit.
  • Mistake: "5" + 5 — Fix: cast first: int("5") + 5.
  • Mistake: Assuming ** binds left-to-right — Fix: it binds right-to-left: 2 ** 3 ** 2 is 512.
  • Mistake: Using % when you want / on negative numbers — Fix: -7 % 3 is 2 in Python (not -1); remember modulo results share the sign of the divisor.

Professional Tips & Tricks

  • Never use = inside conditions — that is assignment. Use == for comparison.
  • Wrap long boolean conditions in parentheses for readability.
  • Use // and % together to split numbers into digits, coins, or time units.
  • Leverage chained comparisons: 18 <= age < 60 is clearer than two separate checks.
  • Use += for accumulators inside loops.

Key Takeaways

  • Arithmetic: / always floats; // floors; % gives the remainder.
  • Comparisons return True/False; == compares, = assigns.
  • and/or/not combine booleans; and/or short-circuit.
  • Parentheses control precedence — use them liberally.
  • +=, -=, *= are assignment shortcuts.
  • // and % are the real-world workhorses for time, digits, and wrapping.

Next up: Control flow — conditionals and loops that make decisions.

Interactive Lesson Code Snippet
# Operators in action
a, b = 17, 5

print("Addition:", a + b)
print("Division:", a / b)      # float division
print("Floor div:", a // b)    # drops the remainder
print("Modulo:", a % b)        # remainder (17 = 3*5 + 2)

# Comparison + logical operators
score = 85
passed = score >= 40
distinction = score >= 75
print("Passed:", passed)
print("Distinction:", distinction)
print("Passed AND distinction:", passed and distinction)
print("NOT failed:", not (score < 40))

# Precedence: parentheses rule!
print("3 + 4 * 2 =", 3 + 4 * 2)     # 11, not 14
print("(3 + 4) * 2 =", (3 + 4) * 2) # 14

# Assignment shortcuts
total = 10
total += 5   # total = 15
total *= 2   # total = 30
print("Total after shortcuts:", total)
Language: python

Lesson Code (Python)

# Operators in action
a, b = 17, 5

print("Addition:", a + b)
print("Division:", a / b)      # float division
print("Floor div:", a // b)    # drops the remainder
print("Modulo:", a % b)        # remainder (17 = 3*5 + 2)

# Comparison + logical operators
score = 85
passed = score >= 40
distinction = score >= 75
print("Passed:", passed)
print("Distinction:", distinction)
print("Passed AND distinction:", passed and distinction)
print("NOT failed:", not (score < 40))

# Precedence: parentheses rule!
print("3 + 4 * 2 =", 3 + 4 * 2)     # 11, not 14
print("(3 + 4) * 2 =", (3 + 4) * 2) # 14

# Assignment shortcuts
total = 10
total += 5   # total = 15
total *= 2   # total = 30
print("Total after shortcuts:", total)

Console Output

Addition: 22
Division: 3.4
Floor div: 3
Modulo: 2
Passed: True
Distinction: True
Passed AND distinction: True
NOT failed: True
3 + 4 * 2 = 11
(3 + 4) * 2 = 14
Total after shortcuts: 30

Code Visualization Tips

  • 🧠Make a trace table: write each variable, update its value row by row as you read the code.
  • 🧠Say 'evaluate the right side first' out loud for every assignment — that is how Python thinks.
  • 🧠Visualize modulo as a pizza: 17 slices ÷ 5 friends = 3 full slices each, 2 slices left over.

Professional Tips & Tricks

  • ⚡Never use = inside conditions — that is assignment. Use == for comparison.
  • ⚡Wrap long boolean conditions in parentheses for readability.
  • ⚡Use // and % together to split numbers into digits, coins, or time units.

Python Code Judge & Practice Arena

LeetCode Style

Run real Python 3.12 WebAssembly code directly in your browser against automated test suites.

Solved:0 / 20
0 / 370 XP
Challenges:
Problem 1 of 20

Problem 1: Power Multiplier 1

Easy+10 XP
Write a function `bitwise_power_1(n, power_of_two)` that multiplies n by (2 ** power_of_two) using the bitwise left-shift operator `<<`.
Sample Test Cases:
Input: bitwise_power_1(5, 3)
Expected: 40
Input: bitwise_power_1(10, 1)
Expected: 20
main.pyPython 3.12 (WASM)
1
2
3
4
5
6
7
8
9
10
11
12
Press Run Code to test or Submit to verify test cases

Test Your Knowledge

Instant feedback

Quick Check: Lesson 4: Operators & Expressions

1 / 20
What is the output of this floor division code? print(17 // 5, -17 // 5)

Up next · Continue learning

Conditional Branches & Loops

Evaluating truth tables, if/elif/else routing, for and while loops, break, and continue.

9 mins read45 mins
Start next lesson
Previous: Strings — Slicing, Methods & f-StringsNext: Conditional Branches & Loops
Made withbyAmol Shukla·amolshukla.online
ASAmol Shukla

AI Developer, Trainer & Agentic AI Expert building practical learning systems and real-world AI applications.

Explore

  • Projects
  • Courses
  • Prompts
  • Skills
  • Contact
  • Experience
  • Blogs

Connect

  • Resume
  • Contact
© 2026 Amol Shukla·Created withbyamolshukla.online
Back to top