# Worksheet: Python fundamentals

*Tactiverge Academy · Computational Engineering, module 1 · https://tactiverge.win/academy/computational-engineering/#python-fundamentals*

Name: ______________________    Date: ____________

## Learning objectives

Tick each one when you can do it without looking at your notes.

- [ ] Write and run Python 3 programs that perform calculations with numbers, strings and lists.
- [ ] Explain why floating-point results are approximate and compare them safely.
- [ ] Use if/elif/else, for and while to make decisions and repeat work.
- [ ] Write functions with parameters and return values, and reuse them.
- [ ] Simulate a simple physical process by stepping it forward in time.

## Lesson 1: Values, variables and expressions

Your first engineering calculations in Python: numbers, text, lists, the math module and the surprising truth about decimals.

Read online: https://tactiverge.win/academy/computational-engineering/python-fundamentals/values-variables-expressions/

### Check your understanding

1. What does print(7 // 2) display?
   A) 3.5
   B) 3
   C) 1
   D) 4

2. Why does 0.1 + 0.2 print as 0.30000000000000004?
   A) Python has a bug in addition
   B) Decimal fractions like 0.1 cannot be stored exactly in binary, so floats are very close approximations
   C) The computer ran out of memory
   D) print always adds extra digits

3. Given readings = [4.0, 5.5, 6.1], what is readings[1]?
   A) 4.0
   B) 6.1
   C) 5.5
   D) An error

4. A student writes math.sin(90) expecting 1. What is the problem?
   A) math.sin does not exist
   B) 90 must be written as a string
   C) math.sin expects radians, so this computes the sine of 90 radians
   D) sin(90°) is actually 0

5. What does "3" + "4" produce in Python?
   A) 7
   B) 12
   C) An error
   D) "34"

### My notes

______________________________________________

______________________________________________

## Lesson 2: Decisions, loops, functions and a first simulation

Make programs that decide, repeat and organize their work — then use them to simulate a cup of tea cooling, one step at a time.

Read online: https://tactiverge.win/academy/computational-engineering/python-fundamentals/control-flow-functions-simulation/

#### Project: Programming project: a sensor log checker

Write a Python program, on a computer or in a free online Python environment, that analyses a list of at least 15 temperature readings you make up (include one or two obviously wrong values).

Your program should use **at least two functions** of your own and should:

1. Print the number of readings, the minimum, the maximum and the average.
2. Report the index and value of any reading outside a range you choose, and explain your choice of range in a comment.
3. Print the average with and without the out-of-range readings, clearly labelled.
4. Extend the cooling simulation: find how long the tea takes to reach 60 °C for dt = 1, 0.5, 0.1 and 0.01, and print the results in a small table.

No hardware is required.

**Deliverables**

- A Python 3 file with at least two documented functions
- Program output showing the summary statistics and flagged readings
- A step-size table and two or three sentences on what it shows

### Check your understanding

1. Which numbers does range(4) produce?
   A) 1, 2, 3, 4
   B) 0, 1, 2, 3
   C) 0, 1, 2, 3, 4
   D) 4

2. What decides which lines belong inside an if block in Python?
   A) Indentation
   B) Curly braces
   C) Semicolons
   D) The word end

3. temperature = 25. Which line is printed by: if temperature > 30: ... elif temperature > 20: print("warm") else: print("cool")?
   A) Nothing
   B) warm
   C) cool
   D) Both warm and cool

4. Why might a while loop run forever?
   A) Because while loops are always infinite
   B) Because nothing inside the loop changes the condition towards becoming false
   C) Because the loop has a docstring
   D) Because it uses floats

5. In the cooling simulation, the result changed when the step size shrank from 1.0 to 0.1 minutes. What is the best conclusion?
   A) The program is broken
   B) Larger steps are always more accurate
   C) The coarse step was too large to follow the curve accurately; results should be checked by reducing the step until they stop changing much
   D) Step size never matters

### My notes

______________________________________________

______________________________________________

## Lesson 3: Lists, dictionaries and looping over data

Organise real engineering data in Python: slice and transform lists of sensor readings, describe a component with a dictionary, and loop over tables and grid maps.

Read online: https://tactiverge.win/academy/computational-engineering/python-fundamentals/lists-dictionaries-loops/

### Check your understanding

1. Given values = [5, 6, 7, 8, 9], what is values[1:3]?
   A) [5, 6, 7]
   B) [6, 7, 8]
   C) [6, 7]
   D) [5, 6]

2. After a = [1, 2, 3]; b = a; b[0] = 99, what is a?
   A) [99, 2, 3]
   B) [1, 2, 3]
   C) [99]
   D) An error

3. drive = {"max_rpm": 300}. What does drive.get("gear_ratio", 1) return?
   A) A KeyError
   B) None
   C) 300
   D) 1

4. Which structure best represents a map where each cell is free or blocked?
   A) A single string
   B) A list of lists, indexed as grid[row][col]
   C) A dictionary with one key
   D) One integer

5. A 3-reading moving average is applied to data containing one large spike. What happens to the spike?
   A) It is removed completely
   B) It is spread, at reduced height, across several smoothed values
   C) It becomes larger
   D) The average ignores it automatically

#### Project: Programming project: a wheel log summary

Make up a list of at least 12 dictionaries, each describing one sample from a two-wheeled robot: a time in seconds, a left wheel speed and a right wheel speed in mm/s. Include a stretch where the robot turns and one sample where a speed is impossible (for example, 5000 mm/s). Label the data as made-up in a comment.

Write a program that:

1. Builds separate `left` and `right` lists using comprehensions.
2. Uses `zip` to print, for each sample, whether the robot is going straight, turning left or turning right. Choose and justify a tolerance in a comment.
3. Counts how many samples fall into each category using a dictionary.
4. Applies a 3-sample moving average to each wheel's speeds and prints the result, then writes two sentences on what happened to your impossible value.

No hardware is required.

**Deliverables**

- A Python 3 file using lists, dictionaries, a comprehension and zip
- Printed output showing the per-sample classification and the category counts
- Two or three sentences on how the moving average treated the impossible value

### My notes

______________________________________________

______________________________________________

## Lesson 4: Writing and testing functions

Design functions with clear inputs and outputs, document them with docstrings, and prove they work with small assert-based tests — before a bug reaches the robot.

Read online: https://tactiverge.win/academy/computational-engineering/python-fundamentals/writing-and-testing-functions/

### Check your understanding

1. A function prints a result but has no return statement. What does calling it give back?
   A) The printed text
   B) 0
   C) None
   D) An error

2. Why should a test compare wheel_distance_mm(360, 360, 65) with math.isclose rather than ==?
   A) Because the result involves π and floating-point arithmetic, so it may differ from the hand value in the last digits
   B) Because == cannot compare numbers
   C) Because math.isclose is faster
   D) Because the function returns a string

3. Which set of test cases is best for clamp(value, 0, 100)?
   A) 50 only
   B) Ten random values between 0 and 100
   C) 50, -20, 150, 0 and 100
   D) Values computed by calling clamp itself

4. What happens when assert x > 0, "x must be positive" runs with x = -3?
   A) Nothing; assert only prints a warning
   B) x is changed to 3
   C) The program carries on and returns False
   D) An AssertionError with the message "x must be positive" is raised

5. In def adc_to_volts(counts, vref=3.3), what does vref=3.3 mean?
   A) vref is always 3.3 and cannot be changed
   B) vref defaults to 3.3 when the caller does not supply it
   C) The function returns 3.3
   D) counts must equal 3.3

#### Project: Programming project: a tested toolkit

Build a small Python module of engineering helpers, each with a docstring and a test function.

1. `average(values)` — decide, and document, what it should do for an empty list.
2. `celsius_to_fahrenheit(c)` — test it with values you can check by hand: 0 °C is 32 °F and 100 °C is 212 °F, and −40 is the same in both scales.
3. `wheel_distance_mm(ticks, ticks_per_rev, diameter_mm)` from this lesson.
4. `clamp(value, low, high)` — add a test that checks the result is never outside the range for every whole number from −200 to 200.

Then deliberately break each function in a small way (change an operator, a sign or a boundary) and confirm that at least one of your tests fails. If a break goes unnoticed, add a test that catches it.

No hardware is required.

**Deliverables**

- A Python 3 file with four documented functions and a test_ function for each
- Output showing every test passing
- A short list of the deliberate bugs you introduced and which test caught each one

### My notes

______________________________________________

______________________________________________

## Lesson 5: Reading files and CSV data

Save and load data with Python's standard library: write and read text files safely, parse CSV logs with the csv module, cope with missing values and save your results.

Read online: https://tactiverge.win/academy/computational-engineering/python-fundamentals/files-and-csv-data/

### Check your understanding

1. What happens if you run open("results.csv", "w") and results.csv already exists?
   A) Python refuses and raises an error
   B) The new data is added to the end of the file
   C) The existing contents are erased and the file starts empty
   D) Python asks for confirmation

2. Each line read from a text file such as temps.csv is…
   A) A string, usually ending in a newline character
   B) A float
   C) A list of numbers
   D) A dictionary

3. Why use the csv module rather than line.split(",")?
   A) split is not allowed on strings read from files
   B) The csv module converts every value to a number automatically
   C) The csv module makes files smaller
   D) It correctly handles quoted fields that themselves contain commas

4. A log has 50 rows and 3 have an empty temperature field. What is the most honest summary?
   A) Report the mean of the 47 valid readings and state that 3 were missing
   B) Treat the missing values as 0 and report the mean of 50
   C) Delete the 3 rows from the original file
   D) Report only the mean, since missing values are unimportant

5. Your program raises FileNotFoundError for "log.csv", but the file is definitely on your computer. What is the most likely cause?
   A) The file is too large to open
   B) Python is looking in a different current working directory
   C) CSV files cannot be opened with open
   D) The file must be renamed to log.txt

#### Project: Programming project: a log processor

Write a program in two parts.

**Part 1 — make the data.** Write a CSV file called `room_log.csv` with columns `time_s`, `temp_c` and `humidity_pct` and at least 30 rows of made-up readings, one every 10 seconds. Put a comment saying the data is made up. Leave at least two fields empty and put the text `ERR` in one.

**Part 2 — analyse it.** Using `csv.DictReader`:

1. For each of the two measurement columns, count the valid, empty and non-numeric values. (Hint: a value is numeric if it is not empty and not `ERR`; the lesson on errors shows a more general method.)
2. Compute the minimum, maximum and mean of each column using only valid values.
3. Write the results to `room_summary.csv`, one row per column, and print the summary file.
4. Confirm that `room_log.csv` is unchanged by printing its first three lines at the end.

No hardware is required.

**Deliverables**

- A Python 3 program that writes room_log.csv and produces room_summary.csv
- Printed output showing counts of valid and missing values for each column
- The contents of room_summary.csv

### My notes

______________________________________________

______________________________________________

## Lesson 6: Errors, tracebacks and debugging

Read Python's error messages with confidence, handle expected problems with try and except, and find silent logic bugs with a systematic debugging method.

Read online: https://tactiverge.win/academy/computational-engineering/python-fundamentals/errors-and-debugging/

### Check your understanding

1. Where should you start reading a Python traceback?
   A) The first line, "Traceback (most recent call last)"
   B) The middle entry
   C) The last line, which names the exception and describes it
   D) It does not matter; all lines say the same thing

2. float("ERR") raises which exception?
   A) ValueError
   B) TypeError
   C) NameError
   D) KeyError

3. Why is a bare except: (catching every exception) usually a bad idea?
   A) It makes the program run slower
   B) It is not valid Python
   C) It only catches syntax errors
   D) It also hides unexpected bugs such as typos, so the program carries on silently with wrong results

4. A program runs without any error message but prints a wrong average. What kind of error is this?
   A) A syntax error
   B) A logic error
   C) A runtime exception
   D) A hardware fault

5. You suspect a bug somewhere in a 200-line data-processing script. What is a good first step?
   A) Rewrite the whole script from scratch
   B) Check the data at the halfway point to see whether it is already wrong there
   C) Change several lines at once and see if the output improves
   D) Wrap the whole script in try and except

#### Project: Debugging project: three bugs

The program below is meant to convert a list of temperature readings from °C to °F, skipping any that cannot be read, and print every converted value. It contains **three** bugs.

```python
readings = ["20.5", "21.0", "bad", "22.5", "23.0"]

def to_numbers(texts):
    numbers = []
    for t in texts:
        numbers.append(float(t))
    return numbers

def celsius_to_fahrenheit(c):
    return c * 9 / 5 + 23

values = to_numbers(readings)
for i in range(1, len(values)):
    print(celsius_to_fahrenheit(values[i]))
```

1. Run it and read the traceback. Write down what it tells you before changing anything.
2. Fix the bug the traceback reveals using `try`/`except`, and make the program report how many readings it skipped.
3. Find the two remaining logic bugs using test cases you can check by hand (0 °C is 32 °F; 100 °C is 212 °F) and by printing the loop variable.
4. Add `assert` tests so that each bug would be caught if it came back.

No hardware is required.

**Deliverables**

- The corrected Python 3 program with assert tests
- A short bug log: for each bug, the symptom, how you found it and the fix
- Output showing all four valid readings converted correctly

### My notes

______________________________________________

______________________________________________

---

## Answer key (for self-checking after you try)

**Lesson 1: Values, variables and expressions**

1. B — // is floor division: it keeps only the whole-number part of the result, so 7 // 2 is 3.
2. B — Floats are stored in binary, and 0.1 has no exact binary representation. That is why engineers compare floats with a tolerance, for example using math.isclose.
3. C — List indices start at 0, so index 1 is the second item, 5.5.
4. C — Use math.sin(math.radians(90)), which returns 1.0.
5. D — + joins two strings together. To add the numbers, convert them first, for example int("3") + int("4").

**Lesson 2: Decisions, loops, functions and a first simulation**

1. B — range(n) starts at 0 and stops before n, giving n numbers in total.
2. A — Python uses indentation to group statements. Lines indented under the if (after its colon) are inside it.
3. B — The first condition is false, the second is true, so its block runs and the else is skipped.
4. B — A while loop stops only when its condition becomes false, so the loop body must make progress towards that.
5. C — Stepping simulations approximate a continuous process. Checking that a smaller step gives nearly the same answer is a basic test of a simulation's trustworthiness.

**Lesson 3: Lists, dictionaries and looping over data**

1. C — A slice starts at the first index (1, the value 6) and stops before the second index (3), so it contains indices 1 and 2: [6, 7].
2. A — b = a does not copy the list; both names refer to the same list, so changing it through b is visible through a. Use a.copy() for an independent list.
3. D — The key is missing, so .get returns the default you supplied, 1. Square brackets, drive["gear_ratio"], would raise a KeyError instead.
4. B — A grid has two dimensions, so a list of rows, each a list of cells, matches it naturally and lets you reach any cell with two indices.
5. B — Every window that contains the spike includes it in its mean, so the spike is smeared across up to three outputs. A moving average reduces noise but does not reject outliers.

**Lesson 4: Writing and testing functions**

1. C — A function without return hands back None. Printing only shows the value on screen; it does not make it available to the code that called the function.
2. A — Float results are approximations. isclose accepts tiny differences within a tolerance you choose, while == demands every binary digit to match.
3. C — This covers a typical value, both sides outside the range and both exact boundaries, which is where mistakes such as using < instead of <= tend to hide.
4. D — When the condition is false, assert raises AssertionError carrying your message, stopping the program unless the error is caught.
5. B — A default value is used only when the argument is left out; a caller can still pass a different reference, for example vref=5.0.

**Lesson 5: Reading files and CSV data**

1. C — Mode "w" truncates an existing file without warning. Use a new filename for derived results, and never open raw data in "w" mode.
2. A — Files contain text. You must strip the newline, split the line and convert the pieces with float or int before doing arithmetic.
3. D — A field like "load added, then removed" is quoted in CSV. split would wrongly break it in two; csv.reader and csv.DictReader follow the quoting rules. Values still come back as strings.
4. A — Filling gaps with 0 biases the result and deleting rows from the raw file destroys evidence. Summarise the valid data and say how much was missing.
5. B — A relative filename is searched for in the current working directory. Print os.getcwd() to check, or run the script from the folder that contains the file.

**Lesson 6: Errors, tracebacks and debugging**

1. C — The last line says what went wrong, and the entry directly above it shows the line where it happened. Earlier entries show the chain of calls that led there.
2. A — float accepts a string, so the type is fine, but this string's content is not a number. That is a ValueError.
3. D — Catch only the exceptions you expect and know how to handle. Anything else should stop the program so you can see and fix it.
4. B — Logic errors produce wrong answers without crashing. Finding them needs a test case with a known answer and careful inspection of the program's state.
5. B — Divide and conquer halves the search space with each check. Changing many things at once makes it impossible to know which change mattered.

---

This work is licensed under the Creative Commons Attribution 4.0 International licence (CC BY 4.0): https://creativecommons.org/licenses/by/4.0/. Attribute as: Tactiverge Academy, https://tactiverge.win.
