Skip to main content
PSUT / IoTEngineering learning studio
WORKSPACE
Offline-first portalDr. Mohammad Alja’afreh
Embedded Systems StudioIoT Programming and ApplicationsExperimentsWorkspaces
ENGINEERING WORKSPACE
Home/WSL Laboratories/Lab 5 · Python shell & arithmetic
IoTPSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
Pi foundations / R5
IoT Programming and Applications

Lab 5 · Python shell & arithmetic

Ask Dr. Mohammad · R5 →

The same Python 3 interactive shell.

Design experiment & verify evidence →
R5 · Laboratory mentorAsk about the current experiment, its algorithms or Python notebook.
Ask Dr. MohammadAdaptive practice
Learning workflow · Core IoT & programmingR5 · Python shell & arithmetic
Readiness checksRevision deckEngineering workspaceRecord evidence
R5 · Academic orientation

Scope and objectives

Scope of the experiment

Compare Python arithmetic operators and integer/floating-point behavior without executing arbitrary user code.

The focus of this experiment is to trace Python arithmetic, types and operator precedence. Students then predict integer division, remainder and floating-point results, and check a calculation in the interpreter and explain rounding. 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 Python arithmetic, types and operator precedence.
  • Predict integer division, remainder and floating-point results.
  • Check a calculation in the interpreter and explain rounding.
  • Identify the configured inputs (Left operand; Right operand; Operator; Environment) 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 Python arithmetic, types and operator precedence, predict integer division, remainder and floating-point results, and check a calculation in the interpreter and explain rounding.

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 check a calculation in the interpreter and explain rounding. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting. After completion, continue to Lab 6 · First Python program.

Environment and experimental methodology

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.

R5 / 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.

Ubuntu WSL setup →
Before you run / verification gate

Run python3 in Bash first; type expressions individually at >>>, then exit() to return to Bash.

CONCEPTS / ACTIVE RECALL

Understand the experiment

Scientific architecture · Python arithmetic and expression evaluation

Expression evaluation and precedence — Expression / 2 + 3 * 4; Multiplication / 3 × 4 = 12; Addition / 2 + 12 = 14; Integer object / 14; REPL / prints 14
Scientific concept map: Python expression — Operands and operators; Parser — Precedence / parentheses; Arithmetic — Division / modulo / power; Result object — int or float; REPL output — Print and compare.

Scientific foundations and analytical reasoning

Python arithmetic distinguishes true division, floor division and remainder. For integers a and nonzero b, a=b*(a//b)+a%b.

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 · Numeric representation and operator order

Python integers are exact for ordinary arithmetic, whereas float represents finite-precision binary approximations. Multiplication and division precede addition unless parentheses override precedence. The // operator rounds toward negative infinity, and the remainder obeys a = bq + r for q = a // b.

Worked example and engineering interpretation

For a=-7 and b=3, q=-3 and r=2; 3(-3)+2=-7. Compare 7/3 with 7//3 and 7%3. A result such as 0.1+0.2 may differ slightly from 0.3 in floating point, so use a suitable tolerance rather than exact equality for measured values.

Engineering principles · additional worked teaching example

Python floor division rounds toward negative infinity. For −10//4 the result is −3, and remainder is 2 because −10=4(−3)+2. True division returns −2.5. A zero divisor raises ZeroDivisionError; these expressions are not Bash commands.

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 5 · Python shell & arithmetic

Evaluate Python expressions in the REPL and distinguish Python from Bash.

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: Evaluate Python expressions in the REPL and distinguish Python from Bash.

  1. Evaluate 7 // 3, then 7 / 3 and 7 % 3. Record type and result.
  2. Change left operand to −7 for // and %. Explain floor rounding.
  3. Set right operand to zero for division. Observe the exception.
  4. Use the original Python REPL commands and verify the results. A Bash command prompt is not a Python REPL.

Reference check:

Model boundary:

Independent task and submission evidence

2. Change left operand to −7 for // and %. Explain floor rounding. 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.

TrialChanged settingFixed settingsPredicted resultActual observation / unitsEvidence / uncertainty
A: baselineReferenceRecordPredictRecordRecord
B: one changeRecordSame as APredictRecordRecord
A: repeatRestoreSame as APredictRecordRecord

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

Python precedence handles exponentiation before multiplication and addition; // is floor division, % is remainder with positive divisor. For −13//5 = −3 and −13%5 = 2. The type of / output is float even if integral.

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.

Lab 5 · Python shell & arithmetic: operation pathwayExpression−13 // 5Floor−2.6→−3Remainder−13−(−3×5)=2Verify−13=−15+2Read the active operation, then inspect the accumulated state.

Step 1 of 4 · Expression

Expression

Expression
−13 // 5

Teaching example only; inspect live calculations or real practical evidence separately.

Recall the concept before revealing its explanation.

0 / 3 revealed
R5 · 01 / 08What is floor division?Reveal explanation
Engineering explanation

7 // 2 yields 3; ordinary division yields 3.5.

R5 · 02 / 08What is the REPL?Reveal explanation
Engineering explanation

An interactive Python interpreter, identified by >>>; Python expressions are not Bash commands.

R5 · 03 / 08Which interpreter must be active before entering the five arithmetic expressions?Reveal explanation
Engineering explanation

Run python3 in Bash first; type expressions individually at >>>, then exit() to return to Bash.

R5 · 04 / 08What is the difference between /, // and % for 7 and 2?Reveal explanation
Engineering reasoning

7/2 = 3.5, 7//2 = 3 and 7%2 = 1. Floor division and remainder are related by 7 = 3×2 + 1.

R5 · 05 / 08Why type exit() in the REPL rather than a Bash command?Reveal explanation
Engineering reasoning

The interpreter evaluates Python syntax; exit() returns to the shell, where shell commands belong.

R5 · 06 / 08A student evaluates Python expressions. Select every technically valid statement. A. Python / returns true division for integers. B. Python // floors the quotient for ordinary integer operands. C. The Bash prompt always executes Python syntax. D. Python ** denotes multiplication.Reveal explanation
Applied scenario

Correct: A. Python / returns true division for integers.; B. Python // floors the quotient for ordinary integer operands.

R5 · 07 / 08In Python shell & arithmetic, which command or code executes Evaluate expressions?Reveal explanation
Implementation recall

7 / 2 7 // 2 7 % 2 2 ** 10 round(22 / 7, 3) exit()

R5 · 08 / 08For Python shell & arithmetic, which actual output or state confirms the prescribed practical run succeeded, and what does it not establish?Reveal explanation
Evidence & acceptance

Start python3 in Ubuntu. Enter the five expressions at >>>, without copying the prompt. Expected in order: 3.5, 3, 1, 1024, 3.143. exit() returns to Bash; these are not shell arithmetic commands.

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 studies
Concurrent-device simulation & Monte Carlo research
Distributed digital twin · topology, protocol & battery research
Loading experiment-specific apparatus…
Previous model / additional reference tools
Simulation task

Evaluate Python expressions in the REPL and distinguish Python from Bash.

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 workbenchR5 · Existing model
01 / Explore

Interactive lab simulation

Browser model
R5 · Model-linked instrumentation

Visual observation lens

Back to controls ↑

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.

Open simulation view
Baseline A
Not captured
Comparison B
Not captured

Capture a baseline to begin.

Evidence portfolio →
V19.0 · Contextual AI workspace

Ask your engineering assistants

R5 · current context

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.

Dr. Mohammad · offline
Dr. Mohammad

Offline curriculum-grounded assistance.

Open local tutor
Lab 5 · Python shell & arithmetic

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 CPython REPL expressions executed.

Start python3 in Ubuntu. Enter the five expressions at >>>, without copying the prompt. Expected in order: 3.5, 3, 1, 1024, 3.143. exit() returns to Bash; these are not shell arithmetic commands.

Record the actual output, source (mock/model or physical), and any error. A missing tool, timeout or untested external service is not a pass.

Complete lab-by-lab verification report →Open automated verification center → Ask Engineering Copilot →

Independent theoretical exercises

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

Calculate 7/3, 7//3, 7%3 and 7**3. Repeat floor division and remainder for -7 and 3; verify the identity.

02 · Compare or justify using evidence

Predict the result of 2+3*4**2 versus (2+3)*4**2 and explain precedence and the output types.

03 · Code-output prediction

Code-output prediction · Independent work

Without running Python, predict print(17//5,17%5,-17//5,-17%5,2**4). Verify the negative remainder identity.

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 · R5-01

Predict print(2+3*4, (2+3)*4, 2**3**2).

Intermediate · Calculate or trace

Independent theoretical exercise · R5-02

Predict print(-21//4,-21%4,21/4).

Intermediate · Interpret the result

Independent theoretical exercise · R5-03

Predict type(8/2).__name__ and type(8//2).__name__.

Advanced · Analyze a condition

Independent theoretical exercise · R5-04

Explain and correct print('4'+3).

Advanced · Diagnose or compare

Independent theoretical exercise · R5-05

Predict print(5*2**3%6).

Challenging · Engineering verification

Independent theoretical exercise · R5-06

Give a test set for a safe calculator supporting division.

Step-by-step experimental procedure

Compare Python arithmetic operators and integer/floating-point behavior without executing arbitrary user code.

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.

Left operand7
Right operand3
Operator//
EnvironmentPython REPL

2 · Perform the investigation in order

  1. Evaluate 7 // 3, then 7 / 3 and 7 % 3. Record type and result.
  2. Change left operand to −7 for // and %. Explain floor rounding.
  3. Set right operand to zero for division. Observe the exception.
  4. Use the original Python REPL commands and verify the results. A Bash command prompt is not a Python REPL.

3 · Compare controlled trials

TrialIndependent changeExpected checkObservation
Floor divisionUse reference inputs aboveResult: 2Record actual result
True divisionOperator = /Result: 2.3333333333333335Record actual result
Division by zeroRight operand = 0Status: ZeroDivisionErrorRecord actual result

4 · Analyze and report

Explain quotient and remainder for negative operands and distinguish numeric type from display formatting.

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.

TrialIndependent changeDependent observation
Floor divisionUse reference inputs aboveRecord actual outcome and units
True divisionOperator = /Record actual outcome and units
Division by zeroRight operand = 0Record 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.

Download NotebookOpen Google ColabAll Python notebooks

Independent implementation sequence

  1. Start the Python REPL
  2. Evaluate expressions
02 / Implement

Step-by-step instructions

Before you run / verification gate

Run python3 in Bash first; type expressions individually at >>>, then exit() to return to 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

Start the Python REPL

In WSL, execute this command only.

WSL · Bash
python3
✓ Expected: Python starts and shows the >>> prompt. Use exit() to return to Bash.
Checkpoint The prompt changes to >>>.
02

Evaluate expressions

Enter the following at >>>, not at the Bash prompt. Do not type the >>> characters.

Python REPL
7 / 2
7 // 2
7 % 2
2 ** 10
round(22 / 7, 3)
exit()
✓ Expected: Return to the Bash prompt.
Expected result for each action (6)
  1. 7 / 23.5
  2. 7 // 23
  3. 7 % 21
  4. 2 ** 101024
  5. round(22 / 7, 3)3.143
  6. exit()Return to the Bash prompt.
Checkpoint 3.5, 3, 1, 1024, 3.143; then returns to Bash.

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.

Python / Google Colab laboratory

R5 · 9 notebook cells · 2 executable Python cells

Complete the theoretical investigation first. Run the cells in order, record actual outputs and compare against your prediction.

How to execute

  1. Download this notebook and open Google Colab. Select File → Upload notebook and choose the downloaded .ipynb.
  2. Read the Markdown instructions before each executable cell. Use a Python runtime, run cells from top to bottom, and resolve imports if necessary.
  3. 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
# r5 · Lab 5 · Python shell & arithmetic **PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh** ## Introduction Evaluate Python expressions in the REPL and distinguish Python from Bash. ## 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 Evaluate Python expressions in the REPL and distinguish Python from Bash. **Reference procedure (use the matching simulator/WSL tool where named, not an unrelated service):** 1. Evaluate 7 // 3, then 7 / 3 and 7 % 3. Record type and result. 2. Change left operand to −7 for // and %. Explain floor rounding. 3. Set right operand to zero for division. Observe the exception. 4. Use the original Python REPL commands and verify the results. A Bash command prompt is not a Python REPL. **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
# =====================================================================
# R5 | Code cell 01 | Lab 5 · Python shell & arithmetic
# 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)
Ask Dr. Mohammad about this cell
05Instructions · Markdown
## 3. Implementation Read the comments and variable definitions before execution. Assertions must pass; inspect values, not just completion.
06Python · executable cell
PYTHON · Code cell
# =====================================================================
# R5 | Code cell 02 | Lab 5 · Python shell & arithmetic
# 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.
# =====================================================================
# Repeat the same operation for each configured input so observations are comparable.
for expression, value in [('7 / 2',7/2),('7 // 2',7//2),('7 % 2',7%2),('2 ** 10',2**10),('round(22 / 7, 3)',round(22/7,3))]:
    print(expression,'=',value)
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert (7/2,7//2,7%2,2**10,round(22/7,3))==(3.5,3,1,1024,3.143)
Ask Dr. Mohammad about this cell
07Instructions · Markdown
## 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 python3 ``` ```python 7 / 2 7 // 2 7 % 2 2 ** 10 round(22 / 7, 3) exit() ```
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 left operand to −7 for // and %. Explain floor rounding. 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.