Zum Inhalt springen

English:Python decisions, loops and simple simulations - Computing Year 6

Aus MOOCsWiki Staging
aiMOOC-Siegel aiMOOC

Python decisions, loops and simple simulations - Computing Year 6

QR-Code



Introduction

A real desk lamp suggests a useful question: how could a program decide when a model lamp should be on? This photograph does not show an automatic control system.
A real desk lamp suggests a useful question: how could a program decide when a model lamp should be on? This photograph does not show an automatic control system.

Turn a rule into a working Python simulation. You will store a persistent mode, make a decision for each input pair and repeat the process over a finite list. You will predict the trace, run the code and explain differences between the prediction and the result.

Before you begin: Read short Python assignments and printed output. The earlier course Python fundamentals - variables, input and output - Computing Year 6 is a useful starting point. No previous experience with real sensors is needed. This Year 6 route is an editorial choice within key stage 2 programming; Python is not a statutory Year 6 language requirement.

Your product: A saved, runnable Python 3 program, a trace table, boundary tests and a small justified improvement. A teacher-approved local editor or school coding environment is enough. The simulation only prints words; it does not operate a lamp, a sensor, mains electricity or any other device.

Model contract: Brightness is an invented integer scale from 0 to 100, not lux and not a claim about any device. Commands are exactly Enable, Disable and Hold. The initial mode is disabled. A valid Enable switches the mode on, Disable switches it off and Hold leaves it unchanged. After the command, the model lamp is ON only if the mode is enabled and brightness is less than 30. At exactly 30 it is OFF. Start with the supplied valid inputs; a later extension checks invalid ones.



Model a persistent state and a decision

A state variable remembers something between steps. Our variable enabled holds the Boolean value True or False. It remembers whether the most recent relevant command enabled or disabled the mode. It is not the same thing as the printed lamp output. An enabled model can still print OFF because the current brightness is too high.

Use three questions to decompose each step:

  1. Which command and brightness have arrived?
  2. Does this command change the stored mode?
  3. Given the updated mode and this brightness, what output should be printed?

Order matters. If Enable arrives with brightness 20 while the mode is disabled, update the mode first. The decision then sees True and 20, so the output is ON. Deciding before updating would incorrectly print OFF for that step.


Compare assignment and comparison

enabled = True assigns a value. command == "Enable" asks whether the command equals a particular string. The two equals signs do not change the command. Names and command strings are case-sensitive: "enable" is different from "Enable".

The expression enabled and brightness < 30 is true only when both conditions hold. The lamp cannot turn on merely because it is dark; the mode must also be enabled. Python's Boolean values are written True and False, with capitals and without quotation marks.

Mode after command Brightness Output and reason
False 20 OFF: disabled mode
True 20 ON: enabled and below 30
True 30 OFF: the boundary is not below 30
True 45 OFF: above the threshold

Think first: Enable at 20 is followed by Hold at 45, then Hold at 10. Does Hold at 45 disable the mode? No. It leaves the mode enabled, but that step prints OFF. The later Hold at 10 can therefore print ON without another Enable.

Scope check: A simulation explores rules. Correctly printing ON does not prove that a real room has appropriate lighting or that an electrical installation is safe. We test a stated software model, not physical equipment.



Build a finite loop over input pairs

A list supplies a finite sequence of steps. Square brackets surround the list. Each pair, such as ("Enable", 20), is a tuple: an ordered group of two values. The string is first and the brightness is second. In for command, brightness in steps:, Python takes each pair in turn and assigns its two values to the two loop names. No random choice is involved.

The whole program below is ready to copy into a teacher-approved Python 3 editor as plain code. Preserve indentation. Lines indented under the for belong to its body and run for each pair. Lines indented under an if or elif belong to that branch. Colons introduce these blocks.

steps = [
    ("Hold", 20),
    ("Enable", 20),
    ("Hold", 45),
    ("Hold", 10),
    ("Disable", 10),
    ("Hold", 5),
]

enabled = False
step_number = 0

for command, brightness in steps:
    step_number = step_number + 1

    if command == "Enable":
        enabled = True
    elif command == "Disable":
        enabled = False

    if enabled and brightness < 30:
        lamp = "ON"
    else:
        lamp = "OFF"

    print(step_number, command, brightness, enabled, lamp)


Read the structure before running

  1. The six pairs are the model's input data. They are not readings from a sensor.
  2. enabled = False runs once before the loop, establishing the initial state.
  3. step_number starts at zero and increases once per pair. It counts processed steps.
  4. Enable and Disable update the stored Boolean. Hold matches neither branch, so the mode stays as it was.
  5. The second decision assigns ON or OFF on every step, using the updated mode.
  6. print displays the count, command, brightness, stored mode and output.

The loop finishes after its sixth pair. It does not wait for a Stop command and does not run forever. An empty list would process zero steps and print no rows. A shorter list produces fewer rows; the rule stays the same.

Predict, run, compare: Before pressing Run, write six mode values and six output words. Then save your program, run it and record the actual lines. Correct a mismatch by finding the first differing row, not by changing several rules at once. Paper tracing is useful, but it does not replace execution for this practical objective.

Python source code can be read as ordered instructions. This photograph shows a different, more advanced program; the complete beginner lamp simulation is printed above.
Python source code can be read as ordered instructions. This photograph shows a different, more advanced program; the complete beginner lamp simulation is printed above.


Optional loop demonstration

CS50's original Python loops lecture demonstrates repetition. It is a university-length resource: a teacher may select a short explanation of for and lists, and you may pause to predict the next repeated action. Watching the full lecture or its advanced examples is not required. The written model, code and tasks here are self-contained. Compare what repeats in the film with what repeats for each command pair here; the film does not implement this lamp project.



Trace, test and repair the program

A trace records change over time. Keep separate columns for the input command, brightness, mode after the command and printed output. Do not infer the mode just from ON or OFF: OFF has more than one possible explanation.

Step Command Brightness Mode after command Output
1 Hold 20 False OFF
2 Enable 20 True ON
3 Hold 45 True OFF
4 Hold 10 True ON
5 Disable 10 False OFF
6 Hold 5 False OFF

At step 1, Hold retains the initial False. Step 2 updates the mode to True before checking brightness. Step 3 keeps True but fails the brightness test. Step 4 succeeds without a new Enable. Step 5 changes the mode to False. Step 6 keeps it False even though 5 is below 30.


Make each test answer a question

Boundary test: In a fresh run, use Enable at 29, Hold at 30 and Hold at 31. The outputs must be ON, OFF, OFF, while all three stored modes are True. This distinguishes < 30 from the incorrect <= 30.

State test: Use Enable at 20, Hold at 45 and Hold at 10. Outputs ON, OFF, ON show that an OFF output does not necessarily reset the mode. Use Enable at 20, Disable at 20 and Hold at 0 to check that disabling persists: ON, OFF, OFF.

Loop test: Compare the number of input pairs with the number of printed rows. Six pairs should produce six rows. An empty list should produce none. The count should restart at 1 for a fresh program run, because the variable starts at zero before the loop.

Keep a table with test purpose, input list, predicted result, actual result and conclusion. A matching result supports the tested rule; it is not proof that every imaginable program or real system is correct.


Diagnose three plausible faults

  • If enabled = False is moved inside the loop before each command, the program forgets its mode on every iteration. In the six-step example, step 4 wrongly prints OFF. Restore the one-time initialisation before the loop and rerun the state tests.
  • If the condition uses <= 30, the exact-boundary case wrongly turns ON when enabled. Change only the comparison and repeat 29, 30 and 31.
  • If the decision runs before the command update, Enable at 20 in an initially disabled run prints OFF, and Disable may print an unwanted ON. Restore the input-update-decide order and test both transitions.

For each repair, keep the failed evidence and rerun earlier working cases as regression tests. The goal is an explained improvement, not a screenshot that hides the original mismatch.



Validate inputs and justify an improvement

Document what the first version assumes. Its supplied pairs are well-formed and valid. It does not check arbitrary commands or brightness values. For example, an unknown command can leave the old mode in place; a negative brightness can pass the less-than-30 test. Do not present the core version as a general input validator.

The extension below accepts only the exact three command strings and Python integer values from 0 to 100 inclusive. It rejects floats such as 30.0, text such as "20", and Booleans such as True. This is a deliberately strict representation rule; 30.0 is numerically a whole value but has Python type float, not int. Each list entry must still be a pair of two values.

steps = [
    ("Enable", 20),
    ("Hold", 101),
    ("Hold", 10),
    ("Disable", 10),
    ("Enable", -1),
    ("Hold", 5),
]

enabled = False
step_number = 0

for command, brightness in steps:
    step_number = step_number + 1
    lamp = "OFF"
    status = "Input error"

    valid = (
        command in ["Enable", "Disable", "Hold"]
        and type(brightness) is int
        and 0 <= brightness <= 100
    )

    if valid:
        if command == "Enable":
            enabled = True
        elif command == "Disable":
            enabled = False

        if enabled and brightness < 30:
            lamp = "ON"

        status = "Valid"

    print(step_number, command, brightness, enabled, lamp, status)


Read the guard without guessing

command in [...] tests membership in the allowed list. type(brightness) is int checks the exact Python type. The chained comparison means brightness is at least zero and at most 100. Python evaluates the joined and conditions from left to right and stops at a false one, so unsuitable values do not reach the numeric comparison.

Every iteration first assigns OFF and Input error for that step. Only valid input reaches the mode update and the lamp decision. Invalid input therefore prints OFF, retains the previous stored mode and allows the finite loop to continue. It does not mean the mode has been disabled. The next valid dark Hold can print ON if the mode was already enabled.

Step Input pair Stored mode Output Status
1 Enable, 20 True ON Valid
2 Hold, 101 True OFF Input error
3 Hold, 10 True ON Valid
4 Disable, 10 False OFF Valid
5 Enable, -1 False OFF Input error
6 Hold, 5 False OFF Valid

Step 2 illustrates why preserving state and choosing an output are different actions. Step 5 illustrates why validation must come before updating the mode: an invalid Enable must not enable it. Resetting the output to OFF inside the loop avoids carrying an earlier ON into an error row. Initialising the persistent mode inside the loop would cause the different fault studied earlier.


Improve the model and state its limits

Change the threshold to 40 in a copy. A fresh sequence Enable at 29, Hold at 30, Hold at 39, Hold at 40 should print ON, ON, ON, OFF. Preserve the old tests as a baseline, update the specification and predictions, then run the new version. Explain which results changed and why. Do not quietly change the data to make a failing program appear correct.

This is a single-threshold teaching model. It ignores changing daylight, timing, sensor noise, energy use and physical safety. A future simulation could introduce a documented timer or two switching thresholds, but each extra rule needs its own tests. Never connect this example to real equipment. Use invented data, keep private file paths and personal details out of shared evidence, and credit any sources you use.



Interactive Tasks


Quiz: Test Your Knowledge

What does enabled remember between valid steps? (Whether the stored mode is enabled) (!The current lamp output only) (!The total brightness of every step) (!The name of the Python editor)



The mode is enabled and brightness is exactly 30. What does the stated rule print? (OFF because 30 is not below 30) (!ON because 30 is the boundary) (!ON because enabling overrides brightness) (!Nothing because 30 ends the loop)



Why is enabled initialised before the loop? (To establish the initial mode once and retain later changes) (!To force every input to be Enable) (!To make the loop infinite) (!To convert all commands into integers)



Which order implements the core model correctly? (Read pair, update mode, decide output, print) (!Print, decide output, read pair, update mode) (!Decide output, print, read pair, erase mode) (!Read pair, print old output, erase every command)



What does Hold do to the stored mode on a valid step? (It leaves the previous mode unchanged) (!It always enables the mode) (!It always disables the mode) (!It copies brightness into the mode)



There are six input pairs in the list. How many iterations does the supplied for loop perform? (Six, one for each pair) (!Thirty, one for each threshold unit) (!An unlimited number until Disable appears) (!One because the list has one variable name)



In the guarded version, Hold with brightness 101 follows Enable with brightness 20. What happens on the invalid row? (OFF and Input error are printed while the stored mode remains enabled) (!ON is repeated because every previous output persists) (!The mode becomes disabled and all later rows are skipped) (!The invalid value is silently changed to 100)



Which brightness value meets the guarded version's exact type and range rule? (The integer 30) (!The text value thirty) (!The floating-point value 30.0) (!The Boolean value True)



Why test 29, 30 and 31 while the mode is enabled? (To check the behaviour just below, at and above the threshold) (!To prove the program controls a real lamp safely) (!To avoid testing the boundary itself) (!To make all three outputs identical)



Which evidence best supports the practical objective? (Saved code, predicted traces, actual runs and explained corrections) (!A quiz score without any program execution) (!A photograph of an unrelated lamp) (!Only the claim that the program probably works)





Memory Game

State variable Stores a mode that can persist between steps
Boolean A value represented by True or False
Finite loop Processes the available list and then ends
Guard Checks stated input requirements before an update
Trace table Records inputs, state and output step by step
Regression test Repeats earlier cases after a program change





Drag and Drop

Enable Set the mode to True after a valid input check
Disable Set the mode to False after a valid input check
Hold Keep the stored mode on a valid step
Threshold The comparison boundary used for the lamp decision
Invalid row Print OFF and Input error without changing the mode





Crossword Puzzle

STATE Information retained between steps
DECISION Choice between actions based on a condition
ITERATION One pass through a loop body
BOOLEAN Type with the values True and False
BOUNDARY Edge value a careful test should include
SEQUENCE Instructions or data arranged in an order





LearningApps

Optional extra practice. Choose an appropriate activity with your teacher. If the external collection is unavailable, use the native activities and independent tasks in this course.


Cloze Text

Complete the explanation.
The stored mode is a

value. A list with six pairs causes six loop

. At brightness 30 the original rule prints

even when enabled. A valid Hold leaves the mode

. The guarded program checks input before its state

. Repeating earlier tests after a repair is

testing.



Open Tasks


Easy

  1. Lamp model vocabulary: Explain state, input, decision and output using one supplied pair. Solution guide: the input is a command and brightness, enabled holds the mode, the condition chooses ON or OFF, and print displays the result.
  2. First two lamp steps: Trace Hold at 20 followed by Enable at 20 from the initial state. Solution: False and OFF, then True and ON; update the mode before the second decision.
  3. Python comparison symbols: Explain the different jobs of = and == with two lines from the program. Solution: = assigns a value to a name; == compares two values and yields a Boolean result.
  4. Finite loop count: Predict how many rows lists with zero, two and six pairs produce, then run one changed list. Solution: zero, two and six; actual execution is required for the practical part.


Standard

  1. Run the complete lamp simulation: Save and run the basic program. Compare all six actual rows with your prediction. Expected modes: False, True, True, True, False, False. Expected outputs: OFF, ON, OFF, ON, OFF, OFF. Explain the first mismatch if one occurs.
  2. Lamp threshold test: Write and run the valid three-pair test Enable at 29, Hold at 30, Hold at 31. Expected outputs: ON, OFF, OFF; all three modes remain True. Explain which incorrect comparison this test can reveal.
  3. Persistent mode repair: In a separate copy, deliberately place the initial mode assignment inside the loop before the command check. Run the six-step list and diagnose the changed step 4. Restore the assignment outside and repeat the state tests. Expected faulty step 4: False and OFF instead of True and ON.
  4. Guarded input evidence: Run the guarded program and annotate rows 2 and 5. Solution: row 2 keeps True but prints OFF and Input error; row 5 keeps False and prints OFF and Input error. Neither invalid command input may change the mode.


Advanced

  1. Lamp simulation threshold transfer: Change the threshold to 40 in a copy and run Enable at 29, Hold at 30, Hold at 39, Hold at 40. Expected outputs: ON, ON, ON, OFF. Update the specification and explain why the original boundary expectations must change.
  2. Strict input representation: Design guarded tests for the integer 30, the float 30.0, text 20 and Boolean True. Quote text in actual Python data. Solution: only integer 30 is valid under this explicit representation contract. Explain why numerical equality alone is not the declared type check.
  3. Invalid input followed by recovery: Run Enable at 20, an invalid Hold at 101, then valid Hold at 10. Expected modes stay True throughout; outputs ON, OFF, ON. Explain why the third step is recovery to a valid decision rather than a new Enable.
  4. Simulation quality review: Give a peer the saved program, contract and test table. Ask them to reproduce a boundary test and one invalid-input test. Record one improvement and rerun regression cases. Explain two limits of this software model without connecting it to real equipment.



Learning Check

  1. Stored lamp mode assessment: From disabled mode, trace Enable at 20, Hold at 45, Hold at 10. Give both modes and outputs.
  2. Loop placement assessment: Explain why moving enabled = False inside the loop can break the model. Identify a revealing input sequence.
  3. Boundary comparison assessment: Predict Enable at 29, Hold at 30, Hold at 31 under the original rule and explain the boundary.
  4. Guard preservation assessment: In the guarded version, the mode is False and Enable arrives with brightness -1. What is the mode, output and status? What does a later Hold at 5 print?
  5. Executable simulation assessment: Submit runnable code, one predicted and actual trace, one boundary test and a documented improvement with regression results.
  6. Simulation limits assessment: Explain why correct printed output does not demonstrate safe real-world lamp control.


Worked checks and assessment guidance

  1. Modes are True, True, True. Outputs are ON, OFF, ON. The middle OFF is caused by brightness, not by disabling the mode.
  2. It erases remembered mode before every command. Enable at 20 followed by Hold at 10 should yield ON, ON; the faulty placement yields ON, OFF. The initial assignment belongs before the loop.
  3. The outputs are ON, OFF, OFF, with mode True throughout. The strict less-than condition excludes exactly 30; a less-than-or-equal fault changes the middle result.
  4. The invalid Enable leaves the mode False and prints OFF with Input error. The later valid Hold keeps False and prints OFF with Valid. Validation must precede the state update.
  5. Assess actual execution separately from conceptual answers. The program must retain mode across steps, process the finite list once, update before deciding and match the declared threshold. If the guarded extension is claimed, require its invalid-input and recovery tests. Paper tracing alone leaves execution pending.
  6. The program processes invented brightness data and prints words only. It does not sense a room, measure illumination, address noisy hardware or prove electrical safety. No real device connection is part of this course.


Learning evidence

Knowledge: Explain persistent state, Boolean decisions, assignment versus comparison, the finite loop and the exact threshold.

Practical product: Save and actually run a Python 3 simulation using the supplied invented inputs. Record the initial state and the state/output for every pair.

Testing: Retain predicted and actual traces, a boundary test, a state-preservation test and an explained correction or improvement. If claiming the guarded extension, demonstrate rejected input and subsequent valid recovery.

Transfer: Change the threshold in a saved copy, update the contract and predictions, and rerun earlier appropriate tests.

Completion distinction: Native quiz answers support knowledge evidence. Practical competence requires actual program execution and reproducible results; keep execution pending if only paper tracing is available. This is a software-only learning model, not a hardware control qualification.


OER and Wikipedia

Department for Education: Computing programmes of study, key stage 2. Designing, writing and debugging programs, variables and control structures inform this route. The particular Year 6 Python placement and all lamp contracts, programs, traces and tasks are original editorial teaching examples.

Language reference: Python Software Foundation: More control flow tools, especially if and for. The course uses established Python 3 features and needs no newest-version-specific feature or paid editor.

Photographs, unmodified: Desk Lamp 1 2013-07-12, FASTILY, CC BY-SA 3.0; Python Code, Weal2019, CC0. The real lamp is illustrative, not automatically controlled by this project; the photographed code is a different program.

Video: CS50P, Lecture 2: Loops, CS50 / Harvard, embedded from the original publisher; original course resource page. Optional teacher-selected explanation of loops and lists, not a requirement to watch the full university-length lecture. The film is not copied or redistributed.


Linked learning areas


aiMOOC Projects



Schulfach+




aiMOOCs



aiMOOC Projekte









MOOCwiki · Deutsch

Nach dem Lernen ist vor dem Lernen

Entdecke direkt den nächsten Lernkurs. Weitere Inhalte erscheinen, wenn Du weiter nach unten scrollst.

Zur MOOCwiki-Hauptseite

Mediathek

Suche verfeinern

Dein Lernplan bestimmt, was oben steht. Alle anderen Inhalte bleiben erreichbar. Seitenaufrufe beeinflussen die Auswahl nicht.

Inhalte werden geladen ...

Mediathek wird aus dem Wiki geladen ...