Lite / Building Machines That Respond / Term 1 worksheet
Worksheet: Building Machines That Respond, term 1
Name: Date:
Week 1: Break a machine's job into steps
1. Which step is too vague for a computer?
- Read the soil-moisture sensor at 07:00
- Water until the soil is wet enough
- Close the water valve
2. Why do engineers decompose a big job before coding it?
- It makes the program longer
- Each smaller piece can be designed, tested and fixed on its own
- Computers can only run short programs
3. A step says 'Open the valve until moisture reaches 45 %'. What is the safest improvement?
- Remove the step
- Add 'or 60 s have passed, whichever comes first'
- Change 45 % to 100 %
4. For the watering algorithm, which is an output?
- The soil-moisture reading
- The time 07:00
- The log line with the time and final moisture
5. Why must 'Close the water valve' come after 'Keep the valve open until …'?
- It doesn't matter
- Steps run in order, so closing first would mean no water is delivered
- Computers run the last step first
Week 1: Flowcharts: drawing decisions and loops
1. A tank starts with 55 L of water. The controller runs: while level < 100: level = level + 10 (one pump pass adds 10 L). How many times does the pump run before the loop stops?
Answer: passes
2. In a flowchart, what does a diamond mean?
- An action, such as 'pump on'
- A decision with a yes exit and a no exit
- The end of the algorithm
3. A loop runs while level != 100 and adds 30 L per pass, starting at 0 L. What happens?
- Stops at 100 L
- Stops at 120 L
- Never stops: 90 is followed by 120, so it is never exactly 100
4. Start at 10 L, add 20 L per pass, loop while level < 75. How many passes does the pump make?
Answer: passes
5. Why add 'or 20 passes have run' to the tank loop?
- To make it faster
- So a failed level sensor cannot keep the pump running for ever
- It is needed for the program to start
Week 1: Trace every case with a rule table
1. A sorting machine's decision depends on 4 yes/no sensors and one selector switch with 2 positions. How many different input combinations must a complete test table contain?
Answer: rows
2. A rule table for 3 yes/no sensors has only 7 rows. What is the risk?
- None: 7 is close enough
- One combination has no defined action, so the machine's behaviour there is unknown
- The machine will run more slowly
3. Which test input is most likely to expose a gap in a sorting algorithm?
- The most common part
- A part that triggers two rules at once, such as large AND metal
- No part at all, every time
4. A machine has 4 yes/no sensors. How many rows does a complete rule table need?
Answer: rows
Week 2: Your first Python program: battery runtime
1. A sensor node runs from a 2500 mAh battery and draws a steady 50 mA. A program computes hours = 2500 / 50 and then minutes = hours * 60. What value does minutes hold, in minutes? (Ignore the battery ageing or the voltage dropping.)
Answer: min
2. What does print("3 + 4") show?
- 7
- 3 + 4
- An error
3. What does Python do with # battery capacity in mAh?
- Stores it in a variable
- Ignores it: it is a comment for people
- Prints it
4. Using the same formula, a 3000 mAh battery powers a 25 mA device. How many days is that?
Answer: days
5. Which variable name is best for a current measured in milliamps?
- c
- current
- current_ma
Week 2: How the interpreter reads your program
1. Trace this Python by hand: x = 8; x = x + 1; x = x * 4; x = x - 20; print(x). What number is printed?
Answer:
2. a = 5; b = a * 2; a = 100; print(b). What is printed?
- 10
- 200
- An error
3. Which program raises a NameError?
- x = 3 then print(x)
- print(y) then y = 3
- z = 3 then z = z + 1
4. In Python, what does = mean in total = total + 5?
- total equals total + 5, which is impossible
- Work out total + 5, then store the result in total
- Compare total with total + 5
Week 3: Variables that track a changing machine
1. A robot starts with distance_m = 0.0 and its loop runs distance_m = distance_m + speed_m_per_s * dt_s exactly 7 times, with speed_m_per_s = 2 and dt_s = 0.1. What is distance_m at the end, in metres?
Answer: m
2. Which lines correctly swap a and b?
- a = b then b = a
- a, b = b, a
- b = a then a = b
3. Which is a valid Python variable name?
- 2nd_reading
- second-reading
- second_reading
4. count = 0, then count += 1 runs 3 times, then count = count * 2 runs once. What is count?
Answer:
5. A program runs total_wh = total_wh + 5 but never set total_wh before. What happens?
- total_wh becomes 5
- NameError: total_wh is not defined
- total_wh becomes 0
Week 3: int, float, str and list
1. A machine makes 26 parts and packs them in boxes of 12. What does Python give for 26 // 12 (full boxes)?
Answer: parts
2. What is the type of 7 // 2?
- int
- float
- str
3. reading = "23.5". Which line gives the number 23.9?
- reading + 0.4
- float(reading) + 0.4
- int(reading) + 0.4
4. What does "7" + "2" give?
- 9
- "72"
- An error
5. A machine makes 250 parts and packs 12 per box. How many parts are left over (250 % 12)?
Answer: parts
Week 3: Why 0.1 + 0.2 is not 0.3
1. Which test is the right way to check that a computed voltage v is 3.3 V?
- v == 3.3
- abs(v - 3.3) < 0.001
- v = 3.3
2. Which of these decimals is stored exactly as a Python float?
- 0.1
- 0.3
- 0.25
3. A regulator should output 2.5 V. A test reads 2.502 V. What is the absolute error, |measured − expected|, in millivolts?
Answer: mV
4. What does print(0.1 * 3 == 0.3) show?
- True
- False
- An error
5. A timer adds 0.1 s every tick. What is the most reliable design?
- Keep adding 0.1 to a float
- Count ticks in an int and compute ticks * 0.1 when needed
- Round the float after every addition
Week 4: Translate a formula into Python
1. Which Python line correctly computes V_out = V_in·R2/(R1 + R2)?
- v_out = v_in * r2 / r1 + r2
- v_out = v_in * r2 / (r1 + r2)
- v_out = (v_in * r2 / r1) + r2
2. What does Python give for -3 ** 2?
- 9
- -9
- An error
3. A 2 kg robot moves at 36 km/h. Convert to m/s (divide by 3.6), then use E = 0.5 * m * v ** 2. What is its kinetic energy, in joules?
Answer: J
4. Is 1 / 2 * m * v ** 2 a correct translation of ½mv² in Python 3?
- Yes: 1 / 2 is 0.5 and the rest is left to right
- No: 1 / 2 is 0 in Python
- No: it computes 1 / (2 · m · v²)
5. A robot drives 300 m in 100 s, then 100 m in 100 s. What is its average speed, in m/s?
Answer: m/s
6. Someone writes power_w = voltage_v / current_a. What does a units check say?
- Fine: V/A is watts
- Wrong: V/A is ohms; power is V × A
- Fine if the numbers are small
Week 4: Rearrange the formula, then compute: an LED resistor
1. An LED with a forward voltage of 1.8 V should carry 15 mA from a 9 V supply. Using r_ohm = (v_supply - v_forward) / (current_ma / 1000), what resistance is needed, in ohms?
Answer: Ω
2. Rearrange V = I · R to find I.
- I = V · R
- I = V / R
- I = R / V
3. A program does r = (5 - 2) / 20 with the current in mA. What goes wrong?
- Nothing
- It gives 0.15 Ω, 1000 times too small, because 20 mA must be 0.020 A
- It gives a TypeError
4. A resistor drops 4.5 V at 0.030 A. What power does it dissipate, in watts?
Answer: W
Week 4: The math module: roots, angles and radians
1. A loading ramp is 2.7 m long and rises at 5° to the floor. Python computes height_m = 2.7 * math.sin(math.radians(5)). What is the height, in metres?
Answer: m
2. Which line correctly computes cos of 60°?
- math.cos(60)
- math.cos(math.radians(60))
- math.radians(math.cos(60))
3. A rectangular frame is 80 cm wide and 115 cm tall. Python computes brace_cm = math.sqrt(80 ** 2 + 115 ** 2). How long is the diagonal brace, in centimetres?
Answer: cm
4. Why is math.sqrt(w ** 2) + math.sqrt(h ** 2) not the brace length?
- It is the same thing
- It simplifies to w + h, which is longer than the real diagonal
- It is shorter than the diagonal
5. What is 45° in radians, to 3 decimal places?
Answer: rad
Week 5: Decisions from measurements: if, elif, else
1. A cooling fan is set by: if temp_c >= 45: fan = 100, elif temp_c >= 35: fan = 50, else: fan = 0. What is fan, in %, when temp_c = 44.5?
Answer: %
2. A rule is written: if temp_c >= 35: fan = 50, elif temp_c >= 50: fan = 100. What is wrong?
- Nothing
- The fan can never reach 100 %: any temperature ≥ 50 already matches the first test
- It raises a SyntaxError
3. Which condition tests whether a reading equals the limit?
- if reading = limit:
- if reading == limit:
- if reading := limit:
4. When does the else block in charge_mode run?
- Always
- Only when every condition above it was False
- When the temperature is exactly 45
Week 5: and, or, not: safety interlocks in code
1. guard, operator and fault are each True or False (8 combinations). For how many of the 8 combinations is this Python condition True: guard or operator?
Answer: rows
2. Which condition is True exactly when temp_c is from 0 to 45 inclusive?
- 0 < temp_c < 45
- 0 <= temp_c <= 45
- temp_c >= 0 or temp_c <= 45
3. Why is (guard or operator) and not fault a dangerous interlock?
- It is too strict
- The press can run with the guard open if an operator is present
- It ignores faults
4. How does Python read not fault and guard or override?
- not (fault and guard or override)
- ((not fault) and guard) or override
- not fault and (guard or override)
5. Why does count > 0 and total / count > 50 never divide by zero?
- Python checks the right side first
- If count > 0 is False, Python never evaluates the division
- Division by zero gives 0 in Python
Week 5: Test the edges: boundary values
1. A thermometer reports in steps of 0.5 °C. The alarm rule is if temp_c >= 30: alarm(). As the temperature rises from 28 °C one step at a time, what is the first reading that sets off the alarm, in °C?
Answer: °C
2. A rule should pass readings from 10 to 60 inclusive, in steps of 1. Which set of tests is best?
- 20, 30, 40
- 9, 10, 11, 59, 60, 61
- 0, 100
3. Where should a test's expected value come from?
- From running the code
- From the specification, worked out by hand
- From guessing
4. Version A uses if temp_c <= 0: return 'BLOCK: too cold'. Which input reveals its bug?
- -5
- 0
- 20
5. A rule has three thresholds. Using on, just-below and just-above tests for each, how many boundary tests is that?
Answer: tests
Week 6: for loops: summarise a sensor log
1. A loop totals and counts these temperature readings (°C): [18.0, 25.4, 31.8, 31.6, 21.9, 26.6]. What is total / count, in °C?
Answer: °C
2. How many times does the body of for r in readings: run if readings has 7 items?
- 6
- 7
- 8
3. What happens with total / len(readings) when readings is []?
- It gives 0
- ZeroDivisionError
- It gives None
4. In a loop that totals readings, where should print(total) go to print the total once?
- Indented inside the loop
- After the loop, not indented
- Before the loop
5. Readings 20, 22, 24 and 26 °C. What is the mean, in °C?
Answer: °C
Week 6: Count, flag and find extremes
1. A loop runs if r > 55: over = over + 1 for each reading r in [62.7, 51.5, 58.6, 63.0, 54.8, 55.0] (°C), starting from over = 0. What is over at the end?
Answer: readings
2. To find the hottest reading in a loop, what should hottest start as?
- 0
- The first reading in the list
- 100
3. Why report the max, the min and a glitch count as well as the mean?
- To make the report longer
- Because a mean can look normal while impossible readings are hidden in it
- Because the mean is usually wrong
4. Readings 18.2, 25.6, 19.9 and 23.4 °C. What is the range, max − min, in °C?
Answer: °C
Week 6: while loops: repeat until it's done
1. A motor is 75 °C hotter than the room. Each minute of cooling multiplies the difference by 0.5. The program runs: while excess > 5: excess = excess * 0.5; minutes = minutes + 1 (starting from excess = 75, minutes = 0). What is minutes when the loop ends?
Answer: min
2. Which while loop never ends?
- n = 0; while n < 5: n += 1
- n = 10; while n > 0: n -= 2
- n = 1; while n != 10: n += 2
3. Which job suits a while loop best?
- Print each of 50 readings
- Keep heating until the water reaches 60 °C
- Add up the readings in a list
4. x = 2. How many times does while x > 5: x = x - 1 run?
- 0
- 1
- It never stops
Week 7: Package a calculation as a function
1. def wheel_speed_m_per_s(rpm, diameter_m): return rpm / 60 * math.pi * diameter_m. What does wheel_speed_m_per_s(150, 0.05) return, in m/s?
Answer: m/s
2. Why is return better than print inside a calculation function?
- return is faster to type
- The returned value can be used in further calculations and tests
- print does not work inside functions
3. def area_m2(width_m, height_m): return width_m * height_m. What does area_m2(3, 0.5) return?
- 1.5
- 3.5
- An error
4. def f(x): x * 2 (no return). What does f(4) give?
- 8
- None
- 4
5. Using v = rpm / 60 × π × d, what speed in m/s does a 0.2 m wheel at 30 rpm give, to 3 decimal places?
Answer: m/s
Week 7: Promises and proof: tests with assert
1. You are testing def current_ma(v, r_ohm): return v / r_ohm * 1000. To write assert abs(current_ma(9, 100) - EXPECTED) < 0.01, work EXPECTED out by hand with Ohm's law. What is it, in mA?
Answer: mA
2. A correct function returns 129.99999999999997 for an expected 130. Which test is right?
- assert result == 130
- assert abs(result - 130) < 1e-9
- assert int(result) == 130
3. Why shouldn't you run the function and paste its output into the test as the expected value?
- It is slower
- The test would then agree with any bug the function has
- assert cannot use numbers
4. Which set of inputs best tests c_to_f?
- 1, 2, 3
- 0, 100, −40
- 100, 100, 100
Week 7: Decompose a program into functions
1. A 10-bit ADC reads raw = 307. to_volts(raw) returns raw * 3.3 / 1023, and to_celsius(v) returns (v - 0.5) * 100 (a TMP36-style sensor: 10 mV per °C with a 0.5 V offset). What is to_celsius(to_volts(307)), in °C?
Answer: °C
2. Which function does one job?
- read_convert_check_and_print(path)
- to_volts(raw)
- do_everything()
3. Why test to_volts and to_celsius separately before the whole pipeline?
- It is required by Python
- If the whole report is wrong, you already know which stages are right
- Separate tests run faster
4. With volts = raw × 3.3 / 1023, how many millivolts is one ADC count, to 2 decimal places?
Answer: mV
Week 8: Read the traceback
1. Which part of a traceback tells you the kind of error?
- The first line, 'Traceback (most recent call last)'
- The last line
- The middle line
2. Which is a logic error?
- if x = 5:
- print(10 / 0)
- A mean computed as total / (count + 1)
3. float("ERR") raises which error?
- TypeError
- ValueError
- NameError
4. A list has 7 readings. What is the largest valid index?
Answer:
Week 8: Reproduce, hypothesise, test: hunting logic bugs
1. readings = [15.0, 22.9, 29.8, 29.6, 19.2]. The buggy code sets total = 0, runs for i in range(1, len(readings)): total = total + readings[i], then calls print(total / len(readings)). What does it print (to 2 decimal places)?
Answer:
2. A program gives a wrong total. What is the best first step?
- Rewrite the whole program
- Find a small input that always shows the wrong total
- Change the < signs to <= and see
3. A function returns after checking only the first reading. What is the most likely cause?
- A misspelt variable
- return is indented inside the for loop
- The list is empty
4. distance_mm differences divided by interval_s are printed as m/s and look 1000 times too big. Best fix?
- Divide the result by 1000 to convert mm/s to m/s
- Multiply by 1000
- Remove the label
Week 8: Catch bad data before it bites
1. A log has the lines ["-999.0","25.8","-999.0","21.4","21.6","19.1","20.0","--"]. The program keeps a line only if float(line) works and -40 <= value <= 125 (the sensor's rated range, °C); otherwise it skips it. How many readings are kept?
Answer: readings
2. Which check rejects the line "130.5" from a sensor rated −40 to 125 °C?
- The conversion check (float fails)
- The plausibility (range) check
- Neither
3. Why is replacing bad lines with 0 a bad idea?
- 0 takes more memory
- 0 looks like a real reading and drags the mean down
- Python cannot store 0
4. Why write except ValueError rather than a bare except?
- It runs faster
- A bare except would also hide real bugs, such as a misspelt name
- Bare except is not allowed
Week 9: Plan the sensor-log checker
1. The safe band is 15–45 °C inclusive. Readings (°C): 44, 33, 28, 29, 20, 23, 49, 49, 24, 12, 33, 24. What percentage of the readings are outside the band?
Answer: %
2. Which test log best checks the safe-band boundary?
- 20.0, 30.0, 40.0
- 10.0, 60.0, 9.9, 60.1
- 100.0, 200.0
3. What should the checker do with an empty log?
- Crash with ZeroDivisionError
- Report 'no readings' and INSPECT
- Report a mean of 0 °C and OK
4. Why write each function's docstring before its body?
- Python requires it
- It fixes what the function promises, which tells you what to code and test
- It makes the program run faster
Week 9: Build it, test it, break it
1. A motor log has the lines ["40.0","","50.6","n/a","","59.7","59.4","45.6","52.3"] (°C). The checker skips any line that float() cannot convert and averages the rest. What mean does it report, in °C?
Answer: °C
2. In what order should you build the checker?
- The whole program, then test it
- One function at a time, each with asserts, then the main program
- The tests last, if there is time
3. decide([10, 60], 0) returns INSPECT. Which line is most likely wrong?
- if outside > 0 or malformed > 2:
- if v < SAFE_LOW_C or v > SAFE_HIGH_C: written as <= and >=
- return "OK"
4. Which is the best bug-diary entry?
- Fixed a bug.
- decide([10, 60], 0) gave INSPECT. Hypothesis: edges treated as outside. A probe showed outside = 2. Fixed <= to <. Added assert.
- Changed some signs until it passed.