Loading...
Random behaviour and unexpected input both need controlled handling. Design the allowed outcomes and failure paths before assuming that a single successful run proves correctness.
What you'll be able to do
A random-number function has a stated interval and distribution. Python randint(a,b) includes both endpoints; randrange(a,b) excludes b. A simulated six-sided die therefore needs six equally likely integer outcomes, not a rounded floating value that accidentally gives unequal endpoint probabilities.
Pseudorandom sequences are generated algorithmically from internal state. A seed can reproduce a sequence for debugging, provided the generator and conditions are controlled. Reproducibility does not establish that a simulation accurately models the real process, and an ordinary simulation generator is not automatically suitable for security keys.
An exception reports an abnormal execution condition such as invalid numeric conversion or a missing file. A try block identifies an operation that may fail; a matching handler supplies a defined response. Catch the exception types that the program can meaningfully handle.
Catching every exception and continuing with fabricated data can hide programming faults. Prefer a clear error or a request for corrected input when recovery is possible. Code after a failed conversion must not assume the intended value was assigned, and a cleanup path may be needed for resources.
Use representative valid values, invalid text, empty input and relevant boundary cases. For random code, test constraints such as every generated die value being between 1 and 6, then evaluate distribution over many trials where appropriate. A small sample need not contain each outcome equally often.
Separate input conversion from the main calculation so that a failed conversion cannot masquerade as a legitimate result. Log or present useful context without exposing sensitive data. A controlled failure path is part of the specification, not an optional cosmetic message.
from random import Random
rng = Random(42)
roll = rng.randint(1, 6)
try:
count = int("three")
except ValueError:
print("Enter a whole number")
assert 1 <= roll <= 6Scroll horizontally to see the full code or table.Attempt the task before opening its worked response. Record each change of state, explain the rule used, and check the result against the original requirements. Code examples labelled Python 3 use that language’s conventions; pseudocode states its own assumptions.
Common mistakes to avoid
Key takeaways
Test yourself
Answer a few questions, then review anything you missed.
Start with the quiz above to check the key ideas. You can also choose another topic from the practice library.