All courses › Programming with Python

Programming with Python (Python): free practice, theory and problems

A program is a recipe that the computer follows line by line. In Python you store values in variables, calculate with them and print the result. As an engineer you use this to automate calculations, read measurement data and test ideas quickly, instead of typing the same thing into a calculator a hundred times.

4 parts80 problems16 concepts explainedPractice examFree
Start practising for free →

Contents

  1. Python basics
  2. Loops and conditions
  3. Functions and data structures
  4. Files, errors and modules

1. Python basics

What is it about?

A program is a recipe that the computer follows line by line. In Python you store values in variables, calculate with them and print the result. As an engineer you use this to automate calculations, read measurement data and test ideas quickly, instead of typing the same thing into a calculator a hundred times.

Everything in Python has a type. The type decides what you can do with a value: you can calculate with numbers, and you can slice and join text.

Concepts and formulas

How to solve the problems

  1. Read the code line by line, and write down the value of every variable after each line.
  2. Find the type of each value (int, float or str) before you calculate.
  3. Evaluate expressions in the right order: parentheses, then **, then * / // % from the left, and finally + -.
  4. Check whether the result is an integer or a float, and how it is printed.

Example

A sensor sends the text "L=1234mm". We want the length in meters:

s = "L=1234mm"
mm = int(s[2:-2])
m = mm / 1000
print(m, mm // 1000, mm % 1000)
  1. s[2:-2] starts at index 2 (after L=) and stops before the last two characters. This gives "1234".
  2. int("1234") turns the text into the integer 1234.
  3. mm / 1000 gives the float 1.234.
  4. mm // 1000 is 1 (whole meters), and mm % 1000 is 234 (the remaining millimeters).

The output is 1.234 1 234.

Common mistakes

Follow the values line by line and keep track of the types. Most surprises in Python happen because a value has a different type than you think.

Concepts in this part

Practise python basics in the app →

2. Loops and conditions

What is it about?

A program only becomes really useful when it can make decisions and repeat work. Conditions (if) let the program choose a path based on the data, for example switching off a pump when the pressure gets too high. Loops (for and while) repeat code, for example to go through a thousand measurements or to simulate a process minute by minute.

Concepts and formulas

How to solve the problems

  1. Make a table with one column per variable and one row per iteration.
  2. In a while loop, check the condition before every iteration.
  3. Follow the indentation carefully: what happens inside the loop, and what happens after it?
  4. Stop when the condition becomes false or break runs, and read off the values.
  5. Check the first and the last iteration extra carefully. That is where most mistakes happen.

Example

A tank holds 500 L and 20% of the contents is drained every minute. After how many minutes is there less than 100 L left?

V = 500.0
t = 0
while V >= 100:
    V = 0.8 * V
    t += 1
print(t)

Value table (V after each iteration): t = 1: 400, t = 2: 320, t = 3: 256, t = 4: 204.8, t = 5: 163.84, t = 6: 131.07, t = 7: 104.86 and t = 8: 83.89. Now V >= 100 is false, and the loop stops. The output is 8.

Check with mathematics: 500⋅0.8t<100500\cdot 0.8^t < 100 gives t>ln⁡0.2/ln⁡0.8≈7.2t > \ln 0.2/\ln 0.8 \approx 7.2, i.e. 8 minutes.

Common mistakes

Loops and conditions are easiest to understand with a value table. Write down the variables for every iteration, and your answer will rarely be wrong.

Concepts in this part

Practise loops and conditions in the app →

3. Functions and data structures

What is it about?

As a program grows, you split it into functions: small, named pieces that take values in and give a result back. Then you can test each part on its own and reuse it, for example one function that computes stress and one that reads a file of measurements. Data structures decide how you store many values: a list of measurements, a dictionary of material data or a set of unique IDs.

Concepts and formulas

How to solve the problems

  1. Find the values the parameters get in the call (positional, keyword or default).
  2. Go through the function body line by line with those values.
  3. Look for return: what is sent back, and what is only printed?
  4. Keep track of whether a list or dictionary is modified or a new one is created.

Example

def mean_ok(xs, limit=100):
    ok = [x for x in xs if x <= limit]
    return sum(ok) / len(ok)

data = {"A": [98, 102, 97], "B": [101, 99, 150]}
res = {k: mean_ok(v, limit=120) for k, v in data.items()}
print(res["B"])
  1. For the key "B", xs = [101, 99, 150] and limit = 120 (the keyword overrides the default value 100).
  2. The list comprehension keeps the values that are at most 120: [101, 99]. The value 150 is a faulty measurement and is filtered out.
  3. sum(ok) / len(ok) becomes 200 / 2 = 100.

The output is 100.0. It is a float because / is used. Similarly, res["A"] equals 99.

Common mistakes

A function takes parameters and gives back one thing with return. Lists and dictionaries are mutable, and every name that refers to the same object sees the change.

Concepts in this part

Practise functions and data structures in the app →

4. Files, errors and modules

What is it about?

Real programs read data from files (measurements, log files, CSV from a spreadsheet), must cope with bad data and use ready-made tools from modules. This part shows the few things you need to do it safely.

Concepts and formulas

with open("data.txt") as f:
    for line in f:
        print(line.strip())
try:
    x = float(text)
except ValueError:
    x = None

How to solve the problems

  1. Go through the code line by line and write down the value of each variable.
  2. Remember that everything you read from a file or from input() is text until you convert it.
  3. When a line can fail: see which except catches it and jump there.

Example

data = "12;7;x;5"
numbers = []
for s in data.split(";"):
    try:
        numbers.append(int(s))
    except ValueError:
        pass
print(sum(numbers))
  1. split(";") gives ["12", "7", "x", "5"].
  2. int("x") raises ValueError, which is caught, so "x" is skipped.
  3. numbers becomes [12, 7, 5], and the program prints 24.

Common mistakes

From a file: read → strip → split → convert to numbers inside try/except.

Concepts in this part

Practise files, errors and modules in the app →

Example problems with solutions

Here are some of the problems in programming with Python. In the app, calculation problems get new numbers every time, so you can practise until it sticks – and take a graded practice exam before the real one.

Python basics: What does print(7 // 2) print?

Answer: 3

// is integer (floor) division and rounds down.

Loops and conditions: What does the code print?
for i in range(2, 8, 2):
    print(i, end=" ")

Answer: 2 4 6

range(start, stop, step). The stop value is not included.

Functions and data structures: What does a function without a return statement return?

Answer: None

Python returns None implicitly.

Files, errors and modules: You want to add new measurements at the end of log.txt without erasing what is there. Which mode do you use in open("log.txt", ...)?

Answer: "a"

"a" (append) writes at the end. "w" empties the file first, "r" can only read, and "x" fails if the file already exists.

Practise all the problems →

Matches these university courses

The content covers the syllabus found in engineering degrees, for example: