Trace a small saved program and distinguish file path, syntax and arithmetic output.
The focus of this experiment is to trace sequential assignments, input conversion and program output. Students then predict variable state and diagnose a type or syntax error, and execute a saved Python script and reconcile output with a manual trace. The Concepts view explains the operation before the practical work; the Simulation view is used to examine reference and changed inputs, not to substitute for actual measurements.
Learning objectives
Trace sequential assignments, input conversion and program output.
Predict variable state and diagnose a type or syntax error.
Execute a saved Python script and reconcile output with a manual trace.
Identify the configured inputs (Program saved; Correct working directory; Valid syntax; Input integer; Multiplier) and record the corresponding observed outputs with units where applicable.
Compare the reference calculation or decision with an independent implementation or authorized observation; state any discrepancy and the applicable model boundary.
Expected learning outcomes
On completion, students can trace sequential assignments, input conversion and program output, predict variable state and diagnose a type or syntax error, and execute a saved Python script and reconcile output with a manual trace.
Required deliverables
Submit the derivation or state trace for the named operation, the exact reference and changed configurations, the associated simulator or practical evidence, and a short validation statement addressing execute a saved Python script and reconcile output with a manual trace. Separate predicted values from observations.
Prerequisite knowledge and related learning
Review the following catalogue prerequisites before starting. After completion, continue to Lab 29 · GPIO output · LED.
The named Linux/WSL or Python environment and its browser teaching representation; use the setup instructions and actual command output for validation.
Begin with a manual prediction, record the baseline, change one independent condition at a time, and compare the resulting trace or measurements with the original prediction. Record observations and uncertainty separately from reference values. Follow the experiment’s specific procedure, safety limits, and acceptance checks.
R6 / PREPARE
Before starting
Follow the setup guide and use the named terminal or editor. A browser model is not a real GPIO measurement or a running service.
In VS Code create hello.py in ~/pi-labs, paste the Python statement into the file, save with Ctrl+S, then run the Bash command. Do not paste the Python statement into Bash.
CONCEPTS / ACTIVE RECALL
Understand the experiment
Scientific architecture · Python program save, run and debug
Scientific concept map: Source file — Python statements; Interpreter — Parse and compile; Execution — Variables and loops; Error handling — Traceback / line; Output — Correct and rerun.
Scientific foundations and analytical reasoning
A program executes statements in order after parsing; runtime input conversion is distinct from syntax validation and file resolution.
Before operating the equipment or executing the program, derive the expected outcome using the required theoretical work in Experiment. Use the diagram to identify the variables and system boundaries.
Scientific theory · Program execution and input validation
Python parses a source file before executing its statements. A syntax error prevents normal execution; a runtime exception occurs only when an executed operation fails. Names bind to values in the current scope. Input is text until converted, and type conversions can fail for malformed strings.
Worked example and engineering interpretation
Predict what happens when int receives '12' versus '12.5'. A successful syntax check does not guarantee successful input conversion. Verify a normal input, a boundary input and an invalid input, and explain the different failure stages.
Engineering principles · additional worked teaching example
input returns text; int converts a valid integer string; print displays a value but does not return it to a caller. With input '12', int('12')*3 gives 36, whereas '12'*3 gives '121212'. Verify conversion before multiplication.
From theory to experiment
Predict the reference result before operating the workbench; check the actual intermediate state, units and constraints. The existing simulation, implementation and procedure below are distinct sources of evidence.
How to investigate Lab 6 · First Python program
Create, save and execute a Python file.
Analytical investigation means collecting an observation, identifying the mechanism, using a calculation or state trace to explain it, and checking your conclusion against evidence. Controlled comparison means changing one independent variable, holding the remaining relevant conditions constant, and measuring a dependent variable against a baseline. Experimental validation means comparing a predicted result to a reproducible observation or assertion; agreement inside a model does not certify hardware. Evidence-based reasoning connects a specific observation to a theoretical rule and states uncertainty, not merely an opinion. Performance characterization records a named metric and its units across conditions; sensitivity analysis changes one parameter across several values. A threat assessment links an asset, threat, consequence and evidence to a mitigation.
Experiment-specific guided practice
Objective: Create, save and execute a Python file.
Predict value × multiplier, then run the saved-program case.
Change only input and check printed result.
Toggle saved and working directory independently; compare file errors with syntax error.
Create the equivalent short Python file using the actual lab editor instructions and run it with python3.
Reference check:
Model boundary:
Independent task and submission evidence
2. Change only input and check printed result. Record the named input, prediction, actual output and one limitation; restore the original condition and repeat.
Before execution write the independent variable and its levels, dependent observation with units where applicable, baseline, controlled variables, measurement method and expected result. For a state machine use state/event/output rather than inventing a numeric metric. Record failures and repeat the baseline. A weak conclusion is “it works”; a supported conclusion names the changed setting, observed value/state, corresponding rule and one limitation.
Trial
Changed setting
Fixed settings
Predicted result
Actual observation / units
Evidence / uncertainty
A: baseline
Reference
Record
Predict
Record
Record
B: one change
Record
Same as A
Predict
Record
Record
A: repeat
Restore
Same as A
Predict
Record
Record
Completion: submit the filled table, relevant simulator screenshot or terminal/notebook output, reasoning with units/assumptions, and one limitation. Preserve the independent assessment questions; this guide does not fill their answers.
Worked engineering reasoning and boundary conditions
A Python file is executed top-to-bottom; input() produces str, int() performs conversion, and indentation defines suites. Example: n=int('8'); print(n+2) outputs 10. print displays a value and returns None.
Use the diagram to follow the calculation or state progression. Keep the teaching configuration separate from the independent exercise values; compare observations with the actual model and implementation.
Concept animation · operation pathway
Explore the teaching example independently of the simulator. Each step reveals an operation, data relationship or calculated state. The Simulation view has separate editable inputs.
Step 1 of 4 · Read
Read
Read
input text '8'
Convert
Read
input text '8'
Convert
int('8')=8
Evaluate
Read
input text '8'
Convert
int('8')=8
Evaluate
8+2=10
Print
Read
input text '8'
Convert
int('8')=8
Evaluate
8+2=10
Print
10; return None
Teaching example only; inspect live calculations or real practical evidence separately.
Recall the concept before revealing its explanation.
0 / 3 revealed
R6 · 01 / 08Why save the file?Reveal explanation
Engineering explanation
Python executes the saved file, not unsaved editor contents.
R6 · 02 / 08What is the working directory?Reveal explanation
Engineering explanation
The folder from which relative paths are resolved.
R6 · 03 / 08Where should hello.py be saved, and where is python3 hello.py executed?Reveal explanation
Engineering explanation
In VS Code create hello.py in ~/pi-labs, paste the Python statement into the file, save with Ctrl+S, then run the Bash command. Do not paste the Python statement into Bash.
R6 · 04 / 08Why use a saved script rather than only the REPL?Reveal explanation
Engineering reasoning
A file preserves the sequence of statements for repeatable execution and inspection.
R6 · 05 / 08How do you isolate a syntax error?Reveal explanation
Engineering reasoning
Read the traceback location, inspect that line and surrounding delimiters/indentation, correct the file, and rerun with the intended interpreter.
R6 · 06 / 08A Python script has been edited but its old output persists. Select every technically valid statement.
A. Save the file before running it.
B. Verify the path of the script being executed.
C. The interpreter automatically runs every unsaved editor buffer.
D. Changing the filename cannot affect which script runs.Reveal explanation
Applied scenario
Correct: A. Save the file before running it.; B. Verify the path of the script being executed.
R6 · 07 / 08In First Python program, which command or code executes Run the saved file?Reveal explanation
Implementation recall
cd ~/pi-labs
python3 hello.py
R6 · 08 / 08For First Python program, which actual output or state confirms the prescribed practical run succeeded, and what does it not establish?Reveal explanation
Evidence & acceptance
From Ubuntu create ~/pi-labs and open code .; install Windows VS Code with WSL extension if missing. In VS Code create a file named exactly hello.py (not hello.py.txt), paste the print statement, save, and run python3 hello.py from ~/pi-labs. Expected one greeting line. The VS Code launcher itself requires Windows/WSL.
Execution boundary · Real on WSL. Browser simulation below is a teaching model, not execution of Python or firmware. The real commands run in VS Code/WSL; Wokwi is used for Arduino/ESP32 where indicated.
Shared research workbenches · network designer & advanced studiesConcurrent-device simulation & Monte Carlo research
Distributed digital twin · topology, protocol & battery researchLoading experiment-specific apparatus…Previous model / additional reference tools
Simulation task
Create, save and execute a Python file.
Explore the model using its own controls. Record a prediction before changing a condition. Compare the reference with a changed condition, then use the Experiment tab for the procedure, acceptance criteria and notebook. Model outputs and physical observations must remain separate.
Interactive engineering workbenchR6 · Existing model
Original virtual instrument; model signals and execution trace.
Loading instrument…
Awaiting model display.
Experimental instrumentation · A/B
Compare two model conditions
Capture a baseline, change one experimental condition, run the model if required and capture the comparison. Snapshots contain visible controls and display text, not physical sensor readings. Review before exporting.
Ask Dr. Mohammad locally, or prepare an experiment-aware prompt for ChatGPT, Gemini or Claude. The external providers open in their own tabs; nothing is automatically submitted.
Public course objective, displayed commands, source excerpts and procedure. Private assessment content is not collected.
Prepare a contextual AI prompt
0 characters
Common secret and email patterns are redacted on preparation; this is not a comprehensive privacy filter. Review the entire editable prompt, including student work and unpublished research, before sharing. The providers apply their own accounts, privacy settings and limits.
Prepare → review → copy & open your selected provider → paste and submit there.
Run & verify — acceptance checklist
Build verification: Actual hello.py creation and CPython execution checked.
From Ubuntu create ~/pi-labs and open code .; install Windows VS Code with WSL extension if missing. In VS Code create a file named exactly hello.py (not hello.py.txt), paste the print statement, save, and run python3 hello.py from ~/pi-labs. Expected one greeting line. The VS Code launcher itself requires Windows/WSL.
Record the actual output, source (mock/model or physical), and any error. A missing tool, timeout or untested external service is not a pass.
Before the simulation or practical, solve both experiment-specific tasks. List the given inputs, show the intermediate calculation or state trace, identify the expected observation, and state a limitation. Show formulas and intermediate calculations where relevant, or draw the requested state/sequence diagram. These are independent classroom fixtures; where they differ from the reference configuration below, do not treat them as measured values. Compare your predictions with the corresponding experiment afterwards.
01 · Predict and derive using the given inputs
Trace input 5, multiplier 2, and print of their product. Predict outputs for -3 and 0, then explain what happens for a non-integer input.
Engineering method — input returns text; int converts a valid integer string; print displays a value but does not return it to a caller. With input '12', int('12')*3 gives 36, whereas '12'*3 gives '121212'. Verify conversion before multiplication. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
02 · Compare or justify using evidence
Distinguish a missing file, indentation error and ValueError; specify which stage each failure occurs at and an appropriate correction.
Engineering method — input returns text; int converts a valid integer string; print displays a value but does not return it to a caller. With input '12', int('12')*3 gives 36, whereas '12'*3 gives '121212'. Verify conversion before multiplication. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
03 · Debugging
Debugging · Independent work
A script contains n=input(); print(n*4). For input 7 predict its output, correct it for numeric multiplication, and specify one invalid-input test.
Debugging — input returns text; int converts a valid integer string; print displays a value but does not return it to a caller. With input '12', int('12')*3 gives 36, whereas '12'*3 gives '121212'. Verify conversion before multiplication. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
Work is saved locally when browser storage is available. Export it for submission; no remote upload or automatic grade is assigned.
Expanded independent theoretical exercise bank
Progress from calculation and interpretation to diagnosis and controlled engineering design. Complete the questions without opening the simulation first; show intermediate steps.
Foundational · Apply the principle
Independent theoretical exercise · R6-01
For name='Pi'; count=3; print(name*count), predict exact output.
Intermediate · Calculate or trace
Independent theoretical exercise · R6-02
For n=int('7'); n+=2; print(n*3), give intermediate n and output.
Intermediate · Interpret the result
Independent theoretical exercise · R6-03
Predict print('6'+'2',int('6')+int('2')).
Advanced · Analyze a condition
Independent theoretical exercise · R6-04
What does int('4.2') do? Give a safe interpretation when fractional readings are intended.
Advanced · Diagnose or compare
Independent theoretical exercise · R6-05
A file saved as lab.py.txt is run as python lab.py. What failure and correction?
Challenging · Engineering verification
Independent theoretical exercise · R6-06
Give an input/output boundary test plan for a program doubling nonnegative integers.
Step-by-step experimental procedure
Trace a small saved program and distinguish file path, syntax and arithmetic output.
1 · Reference workbench configuration
Use the named reference workbench and its reference inputs. Additional live instruments may have different controls; use the matching instrument. Record virtual and practical results separately.
Program savedYes
Correct working directoryYes
Valid syntaxYes
Input integer5
Multiplier2
2 · Perform the investigation in order
Predict value × multiplier, then run the saved-program case.
Change only input and check printed result.
Toggle saved and working directory independently; compare file errors with syntax error.
Create the equivalent short Python file using the actual lab editor instructions and run it with python3.
3 · Compare controlled trials
Trial
Independent change
Expected check
Observation
Saved script
Use reference inputs above
Printed value: 10
Record actual result
Unsaved
Program saved = No
Status: File not found
Record actual result
Syntax failure
Valid syntax = No
Status: SyntaxError
Record actual result
4 · Analyze and report
Explain the difference between editing, saving, parsing and execution.
Required evidence: Record the named metrics and trace for the reference and changed cases, then attach the corresponding practical command output or device evidence if available.
Model boundary: A closed, deterministic browser model. The existing practical instructions and source files provide independent execution; browser results are not hardware measurements.
Controlled investigation · reproducible evidence
Method. Use the existing reference workbench configuration and the named controlled changes below. A controlled variable stays fixed while the independent variable is intentionally changed; the dependent variable is the resulting observed output. First predict each trial from the Concepts page. Run the baseline, then change only the specified setting and record the outcome. For deterministic traces one execution per case and a repeated verification are sufficient; for timing or stochastic measurements repeat at least five times, recording each run, median and range. Reset to the reference state between independent comparisons.
Trial
Independent change
Dependent observation
Saved script
Use reference inputs above
Record actual outcome and units
Unsaved
Program saved = No
Record actual outcome and units
Syntax failure
Valid syntax = No
Record actual outcome and units
Evidence: attach the completed comparison table, one trace or screenshot per condition, and actual practical terminal/hardware evidence where applicable. Explain any prediction mismatch and distinguish modeled behavior from measured results.
Loading laboratory-specific procedure…
Python / Google Colab notebook
Bounded notebook reference exercise; original device/service commands are reference-only. Validated locally in a fresh Jupyter kernel. Download, then upload to Google Colab.
In VS Code create hello.py in ~/pi-labs, paste the Python statement into the file, save with Ctrl+S, then run the Bash command. Do not paste the Python statement into Bash.
Complete one-time setup first. Copy one command block at a time into the indicated environment. Do not copy prompt characters. Open new terminals where named; variables are terminal-specific. Ctrl+C stops a running foreground command.
01
Create your first file
In WSL create a folder and open it in VS Code.
WSL · Bash
mkdir-p ~/pi-labs
cd ~/pi-labs
code .
✓ Expected: VS Code opens the current directory; confirm the WSL remote indicator for Linux projects.Expected result for each action (3)
mkdir-p ~/pi-labsNormally silent. The requested directory exists afterward; verify with ls -d.
cd ~/pi-labsNormally no output. pwd should show the requested directory. A missing path produces an error; do not continue until corrected.
code .VS Code opens the current directory; confirm the WSL remote indicator for Linux projects.
Checkpoint VS Code shows WSL in the lower-left corner.
02
Create hello.py
In Explorer click New File and name it hello.py. Paste the following Python code; Ctrl+S saves it.
Python file · hello.py
print("Hello from my Raspberry Pi lab!")
✓ Expected: Save this statement in hello.py; running the saved file prints Hello from my Raspberry Pi lab!.
Checkpoint File saved in ~/pi-labs/hello.py.
03
Run the saved file
Return to the WSL terminal.
WSL · Bash
cd ~/pi-labs
python3 hello.py
✓ Expected: Hello from my Raspberry Pi lab! is printed.Expected result for each action (2)
cd ~/pi-labsNormally no output. pwd should show the requested directory. A missing path produces an error; do not continue until corrected.
python3 hello.pyHello from my Raspberry Pi lab! is printed.
Checkpoint Hello from my Raspberry Pi lab!
Experimental notebook
Record your own results. Values are not prefilled or independently verified.
03 / Inspect
Source code and method
Use the inline source or commands in the steps above. No separate source file is required for this foundational lab.
04 / Verify
Evidence of completion
Save the actual terminal output from the checkpoints above. For simulated inputs explicitly record browser model, fakepi, mock or Wokwi. Never present those data as physical measurements. If a checkpoint fails, see the troubleshooting guide.
Download this notebook and open Google Colab. Select File → Upload notebook and choose the downloaded .ipynb.
Read the Markdown instructions before each executable cell. Use a Python runtime, run cells from top to bottom, and resolve imports if necessary.
Perform the baseline and controlled changes. Save the notebook with actual outputs and your written interpretation.
Execution scope: Default computational cells passed isolated local Python execution; physical equipment and live services require separate verification.
01Instructions · Markdown
# r6 · Lab 6 · First Python program
**PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh**
## Introduction
Create, save and execute a Python file.
## How to run
1. Download this notebook from the laboratory page. Open Google Colab → File → Upload notebook.
2. Select a Python CPU runtime. Run cells from top to bottom using Shift+Enter, or Runtime → Run all.
3. Read the printed observations and assertions. Change one parameter at a time and rerun the relevant cell.
4. Save your own outputs and compare them to the portal Experiment tab.
**Execution boundary:** Bounded notebook reference exercise; original device/service commands are reference-only. Do not run the hardware or service commands in Colab. No real credentials are needed. The notebook is self-contained.
02Instructions · Markdown
## Experiment-specific preparation
Create, save and execute a Python file.
**Reference procedure (use the matching simulator/WSL tool where named, not an unrelated service):**
1. Predict value × multiplier, then run the saved-program case.
2. Change only input and check printed result.
3. Toggle saved and working directory independently; compare file errors with syntax error.
4. Create the equivalent short Python file using the actual lab editor instructions and run it with python3.
**Evidence:**
**Boundary:**
03Instructions · Markdown
## 1. Objectives and reference condition
- Reproduce the specific computational mechanism in this laboratory.
- Inspect the output, compare the reference condition with a changed or rejected condition where implemented, and explain any discrepancy.
- Distinguish actual local Python execution from mock, physical and external-service observations.
## 2. Environment check
04Python · executable cell
PYTHON · Code cell
# =====================================================================
# R6 | Code cell 01 | Lab 6 · First Python program
# Purpose: 1. Objectives and reference condition - Reproduce the specific computational mechanism in this laboratory. - Inspect the output, compare the reference condition with a changed or rejected condition where implem
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
import sys
print("Python",sys.version.split()[0])
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert sys.version_info >= (3,10)
## 3. Implementation
Read the comments and variable definitions before execution. Assertions must pass; inspect values, not just completion.
06Python · executable cell
PYTHON · Code cell
# =====================================================================
# R6 | Code cell 02 | Lab 6 · First Python program
# Purpose: 3. Implementation Read the comments and variable definitions before execution. Assertions must pass; inspect values, not just completion.
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
import tempfile, subprocess, sys
from pathlib import Path
# Limit resource lifetime to this block so files, sockets or temporary state are cleaned up.
with tempfile.TemporaryDirectory() as d:
p=Path(d)/'hello.py'; p.write_text('print("Hello IoT")\n')
result=subprocess.check_output([sys.executable,str(p)],text=True).strip()
assert result=='Hello IoT'; print(result)
## Original portal implementation (reference only)
These are the actual laboratory snippets. They are retained for comparison; follow the portal setup for WSL, hardware or services. They are **not** executed by Run all.
```bash
cd ~/pi-labs
python3 hello.py
```
```python
print("Hello from my Raspberry Pi lab!")
```
08Instructions · Markdown
## 4. Results and analysis
Record the actual output and whether the assertions pass. Identify a parameter to vary, state your prediction, repeat the reference calculation, then explain the changed result.
| Trial | Configuration | Observation | Interpretation |
|---|---|---|---|
| A | Reference | | |
| B | One controlled change | | |
| C | Reference repeat | | |
**Limitations:** Bounded notebook reference exercise; original device/service commands are reference-only. Notebook success does not certify external equipment or services.
09Instructions · Markdown
## Guided reasoning and evidence
A controlled comparison changes one independent input while keeping the other relevant inputs fixed; the dependent variable is the recorded output. Use this lab’s reference condition above.
**Independent task:** 2. Change only input and check printed result. Record the named input, prediction, actual output and one limitation; restore the original condition and repeat.
| Trial | Input/configuration | Prediction | Observation | Evidence / limitation |
|---|---|---|---|---|
| A | Reference | | | |
| B | Changed input | | | |
| A repeat | Reference | | | |
A conclusion is supported only when it cites the recorded values or observed states and explains them with the experiment theory.