Skip to main content
6 day streak
Skip to lesson
CareerPetalPython field guide
Loading progress...
Course contents
PYTHON FIELD GUIDE

Course contents 72 topics / 15 parts

Full course overviewOriginal coding practice / separate server checks

Essentials first, then internals and engineering trade-offs.

LESSON 04 / VALUES AND CONTROL FLOW

Numbers, truth and safe calculations

Choose the right arithmetic and understand the limits of precision.

FoundationTutorial 10 min core+8 min deep divePython 3.11+ / 2026-10-27
Saved work unavailable

Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.

Before you start

Learners building Python foundations; revisit the preparation topics whenever the vocabulary is unfamiliar.

Explore the connected curriculum and preparation map

Lesson content version 2026-10-27. Suggested core budget: 10 minutes; optional deep dive: 8 more minutes. These are reading/practice estimates, not a timed test.

Suggested preparation and repair routes

If an example or checkpoint feels unclear, revisit the relevant foundation and return. These links do not lock the lesson or claim you passed a prerequisite.

Actual runtime and local-lab boundaries

Browser Python 3.13: fresh isolated worker, 4-second execution, 16 KiB output, 256 MiB Python heap; no outbound network, host processes, interactive input or package installation.

Supported snippets run in the browser; temporary files and SQLite data disappear after each run. Models are labelled conceptual, not traces of your edited source. Full operating-system/framework/cloud labs need separate approval.

Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.

YOU WILL BE ABLE TO
  • Use /, // and % correctly
  • Build boolean expressions
  • Avoid exact float comparisons
01

Division has two jobs

Division can report a ratio or split a count into whole groups and a remainder. Choose the operator for the question you need to answer.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Packing items, paginating results and converting minutes all need whole groups plus leftovers, not merely a decimal ratio.

Words you will see

Quotient
The result of division; // gives its floor.
Remainder
What is left according to a = (a // b) * b + a % b.
Float
A number type used for approximate real-number calculations.

Read three related answers

The sample has 17 items and space for 5 per batch. 17 // 5 gives 3 full batches. 17 % 5 gives 2 items left over, because 3 times 5 plus 2 equals 17. 17 / 5 gives the floating-point ratio 3.4, not a count of complete batches.

For nonnegative item counts and a positive size, the remainder is at least zero and smaller than size. divmod(items, size) returns the same quotient and remainder together. Use it when both values are needed; use one operator when only one answer matters.

Write the boundary rule before calculating

Zero items produce zero full batches and zero leftovers. A batch size of zero cannot divide anything: /, // and % raise ZeroDivisionError. Negative sizes do not describe this packing problem, so exclude them in its input contract rather than inventing a meaning.

If the requirement changes to total boxes required, the leftover items need another box. A nonzero remainder therefore adds one to the full-batch count. Do not round the ratio to the nearest integer; even one leftover needs space.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. items = 17

    Supply the total count.

  2. size = 5

    Supply a positive batch capacity.

  3. print(items // size)

    Display the three full batches.

  4. print(items % size)

    Display the two leftovers.

  5. print(items / size)

    Display the ratio, 3.4, as a separate kind of answer.

/ produces a floating-point result. // floors the quotient; % gives the corresponding remainder. For nonnegative counts, these are useful for pages, batches and time conversions.

Conceptual packing rule for nonnegative counts

Conceptual reasoning steps for the original example, not a live trace of your edited Python.

  1. Count17 items arrive.
  2. GroupThree groups consume 3 × 5 = 15 items.
  3. Remainder17 − 15 leaves 2 items; they are not another full group.
Predict before you run

What do the first two prints describe?

Batch workPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Test an exact fit.

Try: Change items to 15.

The prints become 3, 0 and 3.0.

Test no items.

Try: Change items to 0 while keeping size = 5.

The results are 0, 0 and 0.0; the float ratio still has a float type.

Before you move on

For 12 items and capacity 4, how many full groups and leftovers are there? Is an extra box needed?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

There are 3 full groups and 0 leftovers. Exactly 3 boxes suffice; adding one unconditionally would overcount.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
02

Ask questions with booleans

A boolean is True or False. Comparisons ask questions, and boolean operators combine or reverse the answers.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

An eligibility check often has several requirements. Writing the requirements as readable comparisons makes both the rule and its boundary visible.

Words you will see

Comparison
A question such as age >= 18 that produces a boolean for these numbers.
and
Evaluate the right operand only when the left operand is truthy.
Short-circuit
Skip evaluation of an operand when the result is already determined.

Separate the questions

The first print asks whether age is at least 18 and whether permission is present. Both are true, so the combined result is True. Equality belongs in the comparison if age 18 is allowed; changing >= to > changes the rule at that boundary.

The second print first asks whether divisor is nonzero. It is zero, so and does not evaluate 10 / divisor. The result is False rather than a division error. The left-to-right order matters: doing the division first would fail before the guard could help.

Use combination for logic, not concealment

Use and when both requirements must hold, or when either is sufficient, and not to reverse truth. Parentheses help readers when combinations get long. An if statement is clearer when choosing between actions rather than simply asking a question.

For these boolean operands the results are booleans. In general and and or return one of their operands, not necessarily a bool. Avoid substituting arithmetic such as multiplying flags when you actually mean a readable condition.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. print(age >= 18 and has_permission)

    Both requirements hold, so the result is True.

  2. divisor = 0

    Create the boundary that division cannot accept.

  3. print(divisor != 0 and 10 / divisor > 2)

    The first operand is False; Python skips the division.

Comparisons return True or False. Combine conditions with and, or and not. Python short-circuits: the right side is evaluated only if needed. Prefer a readable condition to clever arithmetic.

Predict before you run

Does the zero divisor cause an error in this sample?

Ask before dividingPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Allow the right side to run.

Try: Set divisor = 2.

10 / 2 is greater than 2, so the second result becomes True.

Require a stricter age.

Try: Change age >= 18 to age > 18.

The first result becomes False at age 18.

Before you move on

If divisor becomes 5, does the second print become True?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

No. The guard now permits division, but 10 / 5 is 2.0 and 2.0 > 2 is False.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
03

Truthiness is context

Truthiness is the rule used to treat a value as true or false in a condition. It does not parse the meaning of written text.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

A configuration value spelled 'False' can accidentally enable a feature if you test only whether its text is nonempty.

Words you will see

Truthy
Treated as true by a condition.
Falsy
Treated as false, such as zero, None or an empty built-in container.
Validation
Checking whether supplied data follows the accepted format and meaning.

Empty and false-looking are different

bool converts a value to its truth value. An empty string has no characters and gives False. The string 'False' contains five characters and gives True. Python does not interpret it as the boolean literal False just because the words look similar.

Zero gives False, while a list containing zero gives True because that list has one element. This rule asks about emptiness of the outer container, not whether all its elements are true. Use explicit comparisons when the inner values matter.

Decide what absence means

Use if items when empty and nonempty are the intended alternatives. Use value is None when zero and empty text are valid supplied values that must not be treated as missing. For textual flags, accept a documented set such as 'true' and 'false' and reject anything else.

Do not use eval to convert external text. That would execute code rather than validate a flag. Calling bool is safe as a truth test but is not a parser for numeric strings or user-facing yes/no words.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. print(bool(""))

    Empty text is falsy.

  2. print(bool("False"))

    Nonempty text is truthy regardless of its spelling.

  3. print(bool(0))

    Numeric zero is falsy.

  4. print(bool([0]))

    A nonempty list is truthy even when its element is zero.

Zero, None and empty containers are false in a condition; nonempty containers are true. A nonempty string such as 'False' is still truthy. Convert and validate external input instead of trusting its spelling.

Predict before you run

Which sample values are truthy?

Truth is not spellingPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Empty the container.

Try: Replace [0] with [].

The last print changes to False.

Compare text and numbers.

Try: Add print(bool("0"), bool(0)).

It displays True False because truthiness does not convert the text to a number.

Before you move on

What truth value does the string '0' have, and how is it different from integer 0?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

The nonempty string '0' is truthy. Integer 0 is falsy. A textual digit and a number are different types with different truth rules.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
DETAILED WALKTHROUGH / NOT JUST A SUMMARY

Where this idea earns its place

Numeric representation is a domain decision. Counts of requests, measurements from a sensor and monetary amounts have different validity and rounding rules. Before choosing operators, decide whether values must be integral, whether negative values are meaningful, which units apply and how missing or invalid values should be reported.

Follow the mechanism step by step

For positive batch sizes, // computes the floored quotient and % the remainder such that the original integer is reconstructed from quotient * divisor + remainder. / produces a float. Python booleans are also integer subclasses, so an isinstance(value, int) check accepts True; that may violate a contract that requires an actual minute count.

Work through a concrete application

Work through 17 items in batches of five: three complete batches and two remaining items. If the task is to allocate enough containers, account for the remainder rather than merely using the quotient. Repeat with zero items and a non-divisible total. Reject a zero batch size before the arithmetic and decide explicitly how negative inputs are handled.

Failure cases and misleading shortcuts

Binary floating point cannot represent every decimal fraction exactly. Equality of a rounded display does not prove equality of stored values. Adding an arbitrary epsilon can hide a real difference, especially near zero or across different scales. For decimal accounting, construct Decimal from decimal strings and define rounding rather than converting an already approximate float.

Cost, ownership and alternatives

Python integers grow to represent larger values, but operations on huge integers cost more than operations on small machine-sized values. Treat O(1) arithmetic as a stated bounded-value model, not an unlimited guarantee. Short-circuit boolean expressions can avoid an unsafe operation, yet they return operands rather than always returning a bool.

Verify the contract

Test equality boundaries, negative values if supported, exact multiples, remainders and division by zero. For approximate comparisons, include values near zero and at the domain's largest scale. Validate input types separately from value ranges and check units; passing every arithmetic test cannot detect that one caller supplied seconds where minutes were expected.

Transfer question: Why can if text be wrong for an environment variable that contains 'false'?

The nonempty string is truthy regardless of its English spelling. Parse a documented set of accepted values, reject unknown spellings and return an actual bool. Do not silently interpret a misspelled security setting as either enabled or disabled.

RECALL BEFORE YOU SCROLL

Can you explain it?

Try from memory. Feedback stays on this page and does not award judged progress.

What is 17 % 5?
TRANSFER THE IDEA

Minutes to hours

Convert 135 minutes to whole hours and remaining minutes.

Your practice starterPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

MAKE THE RULE WORK ON NEW INPUTS

Guided practice and transfer

These are public local learning checks, not certified scores. Edited code is saved only with Save work and place. Run results are not stored as certified scores. Export useful unsaved work before leaving.

A short function primer before you begin

def names a reusable rule. The input names in parentheses are parameters. Indent its body; replace the starter's pass placeholder. The body runs when called, not when defined.

return hands a value back and ends that call. print only displays a value. The public assert checks call your function with fresh fixtures; a false condition raises AssertionError with its message.

Return a value, do not only print itPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

GUIDED PRACTICE

Guided: split a count into batches

Return full batches and leftovers together.

The contract

  • total is a nonnegative integer and size is a positive integer; invalid sizes are outside this exercise.
  • Return an integer tuple (full_batches, leftovers), not a float ratio.
  • Do not change inputs. Zero items and an exact fit both have zero leftovers.
Guided: split a count into batchesPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Inspect 6 public checks

Transparent local learning checks, not exhaustive or tamper-proof grading.

  1. leftovers
    from copy import deepcopy
    args = (17, 5)
    before = deepcopy(args)
    expected = (3, 2)
    result = batch_parts(*args)
    assert type(result) is type(expected) and result == expected, "Return the exact value and type for leftovers"
    assert args == before, "Preserve every supplied input"
    assert all(type(part) is int for part in result), "Respect nested types and ownership promises"
  2. empty count
    from copy import deepcopy
    args = (0, 5)
    before = deepcopy(args)
    expected = (0, 0)
    result = batch_parts(*args)
    assert type(result) is type(expected) and result == expected, "Return the exact value and type for empty count"
    assert args == before, "Preserve every supplied input"
    assert all(type(part) is int for part in result), "Respect nested types and ownership promises"
  3. exact fit
    from copy import deepcopy
    args = (15, 5)
    before = deepcopy(args)
    expected = (3, 0)
    result = batch_parts(*args)
    assert type(result) is type(expected) and result == expected, "Return the exact value and type for exact fit"
    assert args == before, "Preserve every supplied input"
    assert all(type(part) is int for part in result), "Respect nested types and ownership promises"
  4. smaller than batch
    from copy import deepcopy
    args = (2, 5)
    before = deepcopy(args)
    expected = (0, 2)
    result = batch_parts(*args)
    assert type(result) is type(expected) and result == expected, "Return the exact value and type for smaller than batch"
    assert args == before, "Preserve every supplied input"
    assert all(type(part) is int for part in result), "Respect nested types and ownership promises"
  5. unit capacity
    from copy import deepcopy
    args = (7, 1)
    before = deepcopy(args)
    expected = (7, 0)
    result = batch_parts(*args)
    assert type(result) is type(expected) and result == expected, "Return the exact value and type for unit capacity"
    assert args == before, "Preserve every supplied input"
    assert all(type(part) is int for part in result), "Respect nested types and ownership promises"
  6. one over
    from copy import deepcopy
    args = (6, 5)
    before = deepcopy(args)
    expected = (1, 1)
    result = batch_parts(*args)
    assert type(result) is type(expected) and result == expected, "Return the exact value and type for one over"
    assert args == before, "Preserve every supplied input"
    assert all(type(part) is int for part in result), "Respect nested types and ownership promises"
    Why is total / size insufficient?

    It is a ratio, not the promised two integer counts. The rule uses two arithmetic operations and a fixed-size result; cost depends on integer size.

    GUIDED PRACTICE

    Guided: ask an inclusive range question

    Check both boundaries without treating zero as missing.

    The contract

    • Inputs are integers and low <= high.
    • Return a bool that is True exactly when low <= value <= high, including both endpoints.
    • A one-point window and zero are valid. Do not return an integer flag or modify inputs.
    Guided: ask an inclusive range questionPYTHON 3

    Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

    Preparing the editor controls. Run and editing become available when this page is interactive.

    Browser Python limits

    Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

    Inspect 6 public checks

    Transparent local learning checks, not exhaustive or tamper-proof grading.

    1. inside
      from copy import deepcopy
      args = (4, 2, 6)
      before = deepcopy(args)
      expected = True
      result = in_window(*args)
      assert type(result) is type(expected) and result == expected, "Return the exact value and type for inside"
      assert args == before, "Preserve every supplied input"
    2. lower endpoint
      from copy import deepcopy
      args = (2, 2, 6)
      before = deepcopy(args)
      expected = True
      result = in_window(*args)
      assert type(result) is type(expected) and result == expected, "Return the exact value and type for lower endpoint"
      assert args == before, "Preserve every supplied input"
    3. upper endpoint
      from copy import deepcopy
      args = (6, 2, 6)
      before = deepcopy(args)
      expected = True
      result = in_window(*args)
      assert type(result) is type(expected) and result == expected, "Return the exact value and type for upper endpoint"
      assert args == before, "Preserve every supplied input"
    4. below
      from copy import deepcopy
      args = (1, 2, 6)
      before = deepcopy(args)
      expected = False
      result = in_window(*args)
      assert type(result) is type(expected) and result == expected, "Return the exact value and type for below"
      assert args == before, "Preserve every supplied input"
    5. above
      from copy import deepcopy
      args = (7, 2, 6)
      before = deepcopy(args)
      expected = False
      result = in_window(*args)
      assert type(result) is type(expected) and result == expected, "Return the exact value and type for above"
      assert args == before, "Preserve every supplied input"
    6. zero singleton
      from copy import deepcopy
      args = (0, 0, 0)
      before = deepcopy(args)
      expected = True
      result = in_window(*args)
      assert type(result) is type(expected) and result == expected, "Return the exact value and type for zero singleton"
      assert args == before, "Preserve every supplied input"
      Why test type when True == 1?

      Boolean equality alone can accept integer flags. This contract promises a bool. It uses a bounded number of comparisons, with numeric comparison costs depending on integer size.

      TRANSFER / TRY BEFORE OPENING HINTS

      Transfer: count every required box

      The customer now wants capacity for all items, including an incomplete final group.

      The contract

      • total is a nonnegative integer and size is a positive integer.
      • Return the smallest integer number of boxes with enough capacity. Any leftovers require one more box.
      • Zero items require zero boxes; an exact fit must not add an extra box. Preserve inputs.
      Transfer: count every required boxPYTHON 3

      Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

      Preparing the editor controls. Run and editing become available when this page is interactive.

      Browser Python limits

      Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

      Inspect 6 public checks

      Transparent local learning checks, not exhaustive or tamper-proof grading.

      1. partial final box
        from copy import deepcopy
        args = (17, 5)
        before = deepcopy(args)
        expected = 4
        result = boxes_needed(*args)
        assert type(result) is type(expected) and result == expected, "Return the exact value and type for partial final box"
        assert args == before, "Preserve every supplied input"
      2. no items
        from copy import deepcopy
        args = (0, 5)
        before = deepcopy(args)
        expected = 0
        result = boxes_needed(*args)
        assert type(result) is type(expected) and result == expected, "Return the exact value and type for no items"
        assert args == before, "Preserve every supplied input"
      3. exact fit
        from copy import deepcopy
        args = (15, 5)
        before = deepcopy(args)
        expected = 3
        result = boxes_needed(*args)
        assert type(result) is type(expected) and result == expected, "Return the exact value and type for exact fit"
        assert args == before, "Preserve every supplied input"
      4. one item
        from copy import deepcopy
        args = (1, 5)
        before = deepcopy(args)
        expected = 1
        result = boxes_needed(*args)
        assert type(result) is type(expected) and result == expected, "Return the exact value and type for one item"
        assert args == before, "Preserve every supplied input"
      5. one over capacity
        from copy import deepcopy
        args = (6, 5)
        before = deepcopy(args)
        expected = 2
        result = boxes_needed(*args)
        assert type(result) is type(expected) and result == expected, "Return the exact value and type for one over capacity"
        assert args == before, "Preserve every supplied input"
      6. unit capacity
        from copy import deepcopy
        args = (4, 1)
        before = deepcopy(args)
        expected = 4
        result = boxes_needed(*args)
        assert type(result) is type(expected) and result == expected, "Return the exact value and type for unit capacity"
        assert args == before, "Preserve every supplied input"
        Why not round(total / size)?

        Nearest rounding can round down and leave items unpacked. This changed requirement needs a ceiling for nonnegative counts. It uses fixed-count integer operations, not a loop per box.

        A GOOD PLACE TO PAUSE

        Core route complete.

        If you can explain the checkpoint and attempt the practice, move on. Come back for the deep dive when you want the why behind the how.

        Save your core reading milestone

        Floats are approximations

        A float stores an approximation of many decimal fractions. Equality compares the stored values exactly; closeness compares them within chosen tolerances.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Measured distances or calculated fractions can differ by tiny representation errors. Money and fixed decimal policies need a different decision from approximate measurements.

        Words you will see

        Representation error
        The difference between an intended number and the value a representation can store.
        Tolerance
        The accepted absolute or relative difference.
        Decimal
        A standard-library type for decimal arithmetic with an explicit precision and rounding context.

        Explain the surprising comparison

        The sample adds the nearest binary floating-point approximations of 0.1 and 0.2. Their sum is not exactly the stored float for 0.3. The first print is therefore False; Python is comparing the actual stored numbers, not making a random arithmetic mistake.

        math.isclose compares the difference against relative and absolute tolerances. Its defaults accept this tiny difference, so the second print is True. This is not a guarantee that every pair with the same printed decimal appearance is close enough for every application.

        Choose an error policy, not a patch

        For measurements, select tolerances based on units and acceptable error. Near zero, a positive abs_tol can matter because a relative tolerance alone may reject a small nonzero value against zero. For exact decimal rules, construct Decimal values from strings rather than importing a float's approximation.

        Decimal is not infinite precision and does not decide currency rounding rules for you. Integers are preferable for exact counts, or for money in a smallest unit when that models the requirements. Never widen a tolerance merely until a failing calculation happens to pass.

        The original example, step by step

        These steps explain the original code below. They do not change when you edit your own experiment.

        1. import math

          Load the standard-library module providing isclose.

        2. print(0.1 + 0.2 == 0.3)

          Exact comparison detects the stored-value difference.

        3. print(math.isclose(0.1 + 0.2, 0.3))

          The difference fits the default tolerances.

        Many decimal fractions do not have an exact binary representation. Use math.isclose with an appropriate tolerance for measurements, and Decimal from strings for decimal accounting rules.

        Predict before you run

        Why do the sample prints differ?

        Compare approximate measurementsPYTHON 3

        Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

        Preparing the editor controls. Run and editing become available when this page is interactive.

        Browser Python limits

        Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

        Change one thing; explain the difference.

        Test a meaningful difference.

        Try: Replace the isclose call with math.isclose(0.1 + 0.2, 0.4).

        It prints False; a tolerance is not unconditional acceptance.

        Use decimal inputs deliberately.

        Try: Add from decimal import Decimal and print(Decimal("0.1") + Decimal("0.2") == Decimal("0.3")).

        The added print is True for these exact decimal inputs.

        Before you move on

        Would math.isclose(0.0, 0.000001, abs_tol=0.00001) accept the pair, and why?

        Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

        Read a worked answer

        Yes. Their absolute difference is 0.000001, smaller than the supplied 0.00001 tolerance. Whether that error is acceptable remains a domain decision.

        This is a self-check, not a required quiz or a saved score. You can revisit any concept.

        Floor is not truncation

        Floor division rounds a quotient downward, not toward zero. For negative numbers those are different directions.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Signed offsets and bucket boundaries can be wrong if you apply a nonnegative packing intuition to negative inputs.

        Words you will see

        Floor
        The greatest integer not greater than a number.
        Truncation
        Removing a fractional part toward zero.
        Arbitrary-precision integer
        An integer whose storage can grow to represent larger values, subject to available resources.

        Keep quotient and remainder consistent

        -7 / 3 is between -3 and -2. Its floor is -3, so -7 // 3 prints -3. Multiplying -3 by 3 gives -9, and adding the remainder 2 restores -7. int(-7 / 3) instead truncates toward zero and prints -2.

        With a nonzero integer divisor, Python's remainder has the divisor's sign or is zero. The identity using quotient and remainder still holds. Do not apply a positive-remainder rule without also specifying a positive divisor.

        Exact counts still have resource costs

        Python integers do not silently overflow at a fixed 32-bit boundary. But large integers take more memory and arithmetic time as their digit count grows. A claim of constant work should either assume bounded-size numbers or account for that growth.

        Use integer // directly for an exact integer quotient. Converting a huge integer quotient through a float can lose precision or overflow. Use int on a float only when truncation of an approximate value is genuinely the requested operation.

        The original example, step by step

        These steps explain the original code below. They do not change when you edit your own experiment.

        1. print(-7 // 3)

          Floor the negative quotient to -3.

        2. print(-7 % 3)

          Compute the matching remainder 2.

        3. print(int(-7 / 3))

          Show the different truncation result -2.

        4. print((-7 // 3) * 3 + (-7 % 3))

          Reconstruct -7 to check the arithmetic identity.

        -7 // 3 is -3, not -2, because floor moves toward negative infinity. Python integers grow as needed, but big-integer arithmetic still costs time and memory; it is not constant cost for arbitrarily large numbers.

        Predict before you run

        Why is the first result not -2?

        Downward is not toward zeroPYTHON 3

        Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

        Preparing the editor controls. Run and editing become available when this page is interactive.

        Browser Python limits

        Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

        Change one thing; explain the difference.

        Test an exact negative multiple.

        Try: Replace each -7 with -6.

        Floor and truncation both give -2, and the remainder is 0.

        Change the divisor sign.

        Try: Replace every 3 in the sample with -3, including the reconstruction's multiplier.

        The quotient is 2, the remainder is -1, and the reconstruction is still -7.

        Before you move on

        What are -8 // 3 and -8 % 3, and how do you check them together?

        Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

        Read a worked answer

        They are -3 and 1. The check is (-3) * 3 + 1 = -8. Truncating toward zero would give the wrong floor.

        This is a self-check, not a required quiz or a saved score. You can revisit any concept.

        Make the explanation your own.

        Use Save work and place to store notes with your code. Unsaved edits stay in this course tab; export before leaving. Reading milestones remain separate.

        Take a versioned study copy

        Export this lesson's original theory, textual model explanations, worked examples, public exercise checks and local-runtime boundaries for reading/review. This is separate from exporting your private workspace: no learner code, notes, identity, saved place or results are included. Offline server/browser execution is not provided.

        Worked examples and explained concept checkpoints remain included. Reference answers for independent work are excluded unless you explicitly select them. A downloaded answer is not an earned pass.

        REFLECT, THEN CONTINUE

        Make this a milestone.

        Save a self-reported core reading milestone and confidence. Confidence 1-3 schedules a review when none is already set; higher confidence does not create a new review. This is not a code execution pass or proof of mastery. Deep-dive reading is optional and is not tracked separately yet.

        Your account

        Loading account...

        Sign in to save your work across devices.