smartyfy.mrindigi.com

Python Master Course V2 — 012. Assignment and Augmented Assignment

SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 02 · LESSON 012 OF 200

Assignment and Augmented Assignment — Updating Values with Confidence

Level: Beginner to intermediate foundations · Study: 60–90 minutes · Prerequisite: Lesson 011 — Arithmetic Operators and Reliable Calculations

← Course hub

1. Video lesson

Video not yet available. Study the written lesson and run the examples below. A video will be added when a verified lesson recording is available.

2. Learning outcomes

  • Explain how assignment binds a name to a value and how reassignment changes that binding.
  • Distinguish assignment = from equality comparison ==.
  • Use chained assignment, unpacking, and a two-variable swap correctly.
  • Apply arithmetic update operators such as +=, -=, and *=.
  • Trace a sequence of updates, including a numeric type change.
  • Build a stock movement tracker that validates input before updating its state.

3. Concepts and mental models

Assignment gives a name its current meaning

In stock = 20, Python evaluates the expression on the right and binds the name stock to the resulting object. A name must have a value before you read it. In stock = stock + 5, the right-hand side uses the old value, calculates 25, and then binds stock to the result. This is a sequence of instructions, not a mathematical equation.

= assigns; == compares and returns a Boolean. After stock = 20, stock == 20 is True. The comparison does not update the stock.

Assigning several names

Chained assignment: received = sold = 0 evaluates 0 once and assigns it to both names. It is convenient for simple immutable starting values. It does not mean that later reassignment of one name updates the other.

Unpacking: price, quantity = 12, 3 assigns the two values to their corresponding names. In ordinary unpacking, the number of values must match the number of targets; a mismatch raises ValueError. Python evaluates the right-hand values before assigning the left-hand targets. That is why left, right = right, left swaps two values safely.

Augmented assignment expresses an update

stock += 5 adds 5 to the current stock and assigns the result back. For the simple numbers in this lesson, it has a similar effect to stock = stock + 5. Use it when the same quantity is being updated. The name must already exist: new_total += 5 raises NameError if new_total has never been assigned.

Arithmetic update operators
OperatorUpdateIndependent example, starting with x = 10
+=Addx += 3 → 13
-=Subtractx -= 3 → 7
*=Multiplyx *= 3 → 30
/=True divisionx /= 4 → 2.5
//=Floor divisionx //= 4 → 2
%=Remainderx %= 4 → 2
**=Exponentiationx **= 2 → 100

Each table row starts again from 10; the rows are not one continuous program. Division still requires a nonzero divisor, floor division still rounds downward, and the arithmetic rules from Lesson 011 still apply. Other augmented operators are covered with their corresponding topics later.

A useful boundary: augmented assignment is not universally interchangeable with ordinary assignment. Its target is evaluated once, and some mutable objects can be changed in place. Example F provides a small preview of that distinction; deeper work with collections comes later.

4. Progressive runnable examples

Setup: Python 3.10 or later. Save each independent example as lesson012_example.py and run python lesson012_example.py (or python3). Predict the output first, then compare your result with the expected output.

Example A — Reassignment and comparison

stock = 20
stock = stock + 5
print(stock)
print(stock == 25)
print(stock == 20)

Expected output:

25
True
False

The first update reads 20, calculates 25, then rebinds stock. Both comparisons leave that value unchanged.

Example B — Chained assignment, unpacking, and swapping

received = sold = 0
received += 4
print(received, sold)

price, quantity = 12, 3
print(price * quantity)

left, right = "blue", "green"
left, right = right, left
print(left, right)

Expected output:

4 0
36
green blue

Reassigning received does not change sold. The swap captures both original strings on the right before either name is updated.

Example C — Trace several updates in order

points = 10
points += 5
points *= 2
points -= 4
points //= 3
print(points)

remainder = 17
remainder %= 5
power = 3
power **= 2
print(remainder, power)

Expected output:

8
2 9

Trace points as 10 → 15 → 30 → 26 → 8. Each new statement uses the result of the previous one.

Example D — An update can change the numeric type

units = 9
print(type(units).__name__)
units /= 2
print(units)
print(type(units).__name__)

grouped_units = 9
grouped_units //= 2
print(grouped_units)
print(type(grouped_units).__name__)

Expected output:

int
4.5
float
4
int

type(value).__name__ prints a type’s name. True division of these integers produces a float. Floor division of these integers produces an integer. Choose an operator for its required meaning; do not use floor division just to hide a fractional result.

Example E — Updating text

message = "Order"
original_message = message
message += " confirmed"
print(message)
print(original_message)

Expected output:

Order confirmed
Order

Strings are immutable. The update produces a new string for message; the earlier name still refers to "Order".

Example F — Preview: a shared mutable list

A list holds an ordered collection of items. Square brackets create one: ["pen"] is a one-item list. Here, two names refer to the same list.

items = ["pen"]
same_items = items
items += ["notebook"]
print(items)
print(same_items)

items = items + ["eraser"]
print(items)
print(same_items)

Expected output:

['pen', 'notebook']
['pen', 'notebook']
['pen', 'notebook', 'eraser']
['pen', 'notebook']

For this list, += extends the shared object in place. Ordinary items = items + ... creates a new list and rebinds only items. This example explains why you should not assume that every augmented assignment behaves exactly like a rewritten ordinary assignment.

5. Guided real-world project — Daily stock movement tracker

Scenario: A stationery counter records opening stock, delivered items, sold items, damaged items, and the number of items in a full pack. Produce a closing-stock report without allowing negative stock.

Business rules: all movement quantities are nonnegative whole numbers; pack size is a positive whole number; sold plus damaged items cannot exceed opening stock plus deliveries. Validate every input before accepting an update. Keep the opening quantity unchanged so the report can explain the calculation.

print("=== Daily Stock Movement Tracker ===")
try:
    opening_stock = int(input("Opening stock: ").strip())
    received = int(input("Items received: ").strip())
    sold = int(input("Items sold: ").strip())
    damaged = int(input("Items damaged: ").strip())
    pack_size = int(input("Items per pack: ").strip())
except ValueError:
    print("Invalid input: enter whole numbers.")
else:
    if opening_stock < 0 or received < 0 or sold < 0 or damaged < 0:
        print("Stock quantities cannot be negative.")
    elif pack_size <= 0:
        print("Pack size must be positive.")
    elif sold + damaged > opening_stock + received:
        print("Rejected: sales and damage exceed available stock.")
    else:
        closing_stock = opening_stock
        closing_stock += received
        closing_stock -= sold
        closing_stock -= damaged
        full_packs, loose_items = divmod(closing_stock, pack_size)
        print(f"Opening stock: {opening_stock}")
        print(f"Received: +{received}")
        print(f"Sold: -{sold}")
        print(f"Damaged: -{damaged}")
        print(f"Closing stock: {closing_stock}")
        print(f"Full packs: {full_packs}")
        print(f"Loose items: {loose_items}")

Sample input, in order: opening stock 20, received 5, sold 7, damaged 2, pack size 6. After the title and input prompts, the report is:

Opening stock: 20
Received: +5
Sold: -7
Damaged: -2
Closing stock: 16
Full packs: 2
Loose items: 4

Walkthrough: begin with 20, add 5 to get 25, subtract 7 to get 18, and subtract 2 to get 16. divmod(16, 6) produces two full packs and four loose items. opening_stock remains 20 because updating an integer does not mutate the earlier integer object.

Check the invariant: for every accepted report, closing_stock == opening_stock + received - sold - damaged must be true, and closing stock must be nonnegative.

Boundary cases to test
Inputs: opening, received, sold, damaged, pack sizeExpected behavior
0, 0, 0, 0, 6Accept: closing 0, full packs 0, loose items 0.
8, 0, 8, 0, 4Accept: all available stock sold; closing 0.
5, 3, 6, 2, 4Accept: deliveries make the movements possible; closing 0.
5, 0, 4, 2, 4Reject: sales plus damage exceed available stock.
5, -1, 0, 0, 4Reject: negative movement quantity.
5, 0, 0, 0, 0Reject: zero pack size.
Text such as abc or 2.5 for a quantityReject: the input is not a whole-number representation.

6. Common mistakes and professional practices

  • Using = when you mean ==: assign a value with =; test it with ==.
  • Updating before initialization: assign a sensible starting value before using += or another update operator.
  • Writing =+ instead of +=: count =+ 1 assigns positive 1; it does not add one to the existing count.
  • Assuming all updates keep the type: /= changes these integer calculations to floating-point results.
  • Swapping with two ordinary statements: left = right loses the original left value. Use left, right = right, left.
  • Ignoring shared objects: chained assignment does not copy a mutable object. Avoid first = second = [] when you need independent lists.
  • Changing state too early: validate a stock movement before accepting it. Keep original values for a clear report.
  • Unclear quantities: use names such as opening_stock and closing_stock, and keep units consistent.

7. Guided exercises and independent challenge

  1. Start with score = 7, then apply score += 3 and score *= 2. Predict and verify the final value.

    Hint: sequential score updates

    Each statement reads the result of the previous update.

    Worked answer: sequential score updates
    score = 7
    score += 3
    print(score)
    score *= 2
    print(score)

    Expected output:

    10
    20

    Adding three produces 10, then multiplying that value by two produces 20. Reversing the update order would produce 17, so state changes must be traced in sequence.

  2. Initialize a countdown to 10 and subtract three with augmented assignment. Compare countdown -= 3 with countdown =- 3.

    Hint: subtract versus assign a negative

    The minus sign in =- belongs to the new value; -= is one augmented-assignment operator.

    Worked answer: subtract versus assign a negative
    countdown = 10
    countdown -= 3
    print(countdown)
    countdown = 10
    countdown =- 3
    print(countdown)

    Expected output:

    7
    -3

    countdown -= 3 subtracts from the existing value. countdown =- 3 assigns -3 and discards the previous value. Independent starting values make this comparison fair.

  3. Swap two station names using unpacking. Explain why the right-hand values must be captured before the assignments.

    Hint: swap station names

    Python evaluates the entire right-hand side before binding the left-hand names.

    Worked answer: swap station names
    left = "Central"
    right = "Harbour"
    left, right = right, left
    print(left, right)

    Expected output:

    Harbour Central

    The old values are captured before either name changes. Writing left = right followed by right = left would leave both names referring to the old right-hand value.

  4. Start with value = 11 and compare independent runs of value /= 2 and value //= 2. Print each result and type.

    Hint: division result and type

    Reset value to 11 before each operation; true division and floor division have different contracts.

    Worked answer: division result and type
    value = 11
    value /= 2
    print(value, type(value).__name__)
    value = 11
    value //= 2
    print(value, type(value).__name__)

    Expected output:

    5.5 float
    5 int

    True division produces a float for these integer operands. Floor division produces the integer floor. The result type also depends on operand types; floor division with a float operand can produce a float.

  5. Add a returned input to the stock project. Accepted returned items increase stock. Update the business constraint and invariant before changing the code.

    Hint: accepted returned items

    Include returns in available stock before validating outgoing movements, then update the invariant.

    Worked answer: accepted returned items
    opening_stock, received, returned = 20, 5, 3
    sold, damaged, pack_size = 7, 2, 6
    if min(opening_stock, received, returned, sold, damaged) < 0:
        print("Rejected: negative stock quantity")
    elif pack_size <= 0:
        print("Rejected: pack size must be positive")
    elif sold + damaged > opening_stock + received + returned:
        print("Rejected: outgoing items exceed available stock")
    else:
        closing_stock = opening_stock
        closing_stock += received
        closing_stock += returned
        closing_stock -= sold
        closing_stock -= damaged
        print(closing_stock)
        print(divmod(closing_stock, pack_size))
        print(closing_stock == opening_stock + received + returned - sold - damaged)

    Expected output:

    19
    (3, 1)
    True

    This extension assumes all quantities have already been converted to whole numbers. Add a returned-items input to the original conversion handler. Only accepted, usable returned items belong in stock. The revised invariant includes + returned; rejected input must stop before the report.

  6. Choose inputs that produce exactly one full pack, one full pack plus one loose item, and no stock. Record the expected report before running the project.

    Hint: pack boundary reports

    Choose closing stock equal to the pack size, one greater, and zero.

    Worked answer: pack boundary reports
    pack_size = 6
    for closing_stock in [6, 7, 0]:
        full_packs, loose_items = divmod(closing_stock, pack_size)
        print(closing_stock, full_packs, loose_items)

    Expected output:

    6 1 0
    7 1 1
    0 0 0

    Use opening stock 6, 7, and 0 respectively, with received, sold, and damaged all zero and pack size six. These are all valid project inputs. Also test opening five with sold six: that case must be rejected before any accepted stock report.

Independent challenge: extend the tracker with a nonnegative reorder threshold. Print a reorder message when closing stock is at or below that threshold. Test exactly at the threshold, one item below, one above, and a rejected overselling case. Rejected input must never produce an accepted stock report.

8. Knowledge check with explanations

Answer each question before opening its explanation. These are self-check questions; no practice score is invented or saved.

  1. After count = 5; count += 2, what is count?
    Show answer

    7. The update adds two to the current five.

  2. What does count == 7 do?
    Show answer

    It compares count with seven and returns a Boolean. It does not assign a new value.

  3. What is count after count = 5; count =+ 2?
    Show answer

    2. =+ 2 assigns positive two; += 2 would have produced seven.

  4. Can total += 3 initialize a name that does not exist?
    Show answer

    No. The update first needs the current value. Assign total = 0 before accumulating into it.

  5. After a = b = 4; a += 1, what are a and b?
    Show answer

    a is 5 and b is 4. Integers are immutable; a is rebound and b still refers to four.

  6. What does a, b = b, a accomplish?
    Show answer

    It swaps the two values. Python evaluates both right-hand values before assigning to the targets.

  7. After amount = 8; amount /= 2, what are the value and type?
    Show answer

    4.0, a float. True division of these integers produces a floating-point result.

  8. Why must the stock project check sold plus damaged together?
    Show answer

    Both reduce the same available stock. Checking them separately could approve combined movements that make closing stock negative.

9. Mastery checkpoint

Continue when you can distinguish assignment from comparison, trace a sequence of updates, swap two names, explain a type-changing division update, and modify the stock tracker without allowing invalid state. You should also be able to explain why a shared list update differs from an integer reassignment.

Lesson summary: assignment gives names their current values. Augmented assignment expresses an update clearly, but its behavior depends on the objects involved. Reliable programs initialize state, validate changes, and keep an explainable record of the original and final values.

Further reading: Python reference: assignment statements, augmented assignment, and Python FAQ: shared lists.

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.