Skip to content
Tactiverge

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.

40 min · Self-paced · Free

Programs that decide

So far, every program ran each line once, top to bottom. Real engineering code needs to make decisions: if a temperature is too high, raise an alarm. Python uses if, elif (short for "else if") and else:

temperature = 31.5   # °C

if temperature > 30:
    print("Warning: too hot")
elif temperature < 10:
    print("Warning: too cold")
else:
    print("Temperature OK")

Output:

Warning: too hot

Python checks each condition in order and runs the block under the first one that is true, then skips the rest. Two details matter:

  • Each condition line ends with a colon :.
  • The lines that belong to it are indented, conventionally by four spaces. In Python, indentation is not decoration — it defines which lines are inside the if. Inconsistent indentation is a common beginner error.

Conditions use comparison operators: >, <, >=, <=, == (equal) and != (not equal). Note that == tests equality, while a single = assigns a value. You can combine conditions with and, or and not, and Python even allows chained comparisons such as 0 <= value <= 50.

Repeating with for

A for loop runs a block once for each item in a sequence:

readings = [12.1, 12.3, 55.0, 12.2, 12.4]

for r in readings:
    print(r)

Each time around the loop, r holds the next value. To repeat something a set number of times, use range. range(5) produces 0, 1, 2, 3, 4 — five numbers, starting at zero and stopping before 5.

Loops and decisions combine naturally. That reading of 55.0 looks suspicious next to its neighbours. Let us find it:

for i, r in enumerate(readings):
    if r > 50:
        print(f"Reading {i} looks wrong: {r}")

Output:

Reading 2 looks wrong: 55.0

enumerate gives you each item's index along with its value, which is useful when you need to report where a problem is.

Repeating with while

A while loop repeats as long as a condition stays true. Use it when you do not know in advance how many repetitions you need.

A ball is dropped from 100 cm, and each bounce reaches 60% of the previous height. How many bounces until it rises less than 1 cm?

height = 100.0   # cm
bounces = 0

while height > 1.0:
    height = height * 0.6
    bounces += 1      # same as bounces = bounces + 1

print(f"{bounces} bounces, last height {height:.3f} cm")

Output:

10 bounces, last height 0.605 cm

Always make sure something inside a while loop moves it towards finishing. If height never shrank, the loop would run forever.

Functions: naming a piece of work

A function packages a calculation so you can reuse it. You define one with def, give it parameters (inputs) and use return to hand back a result:

def current_ma(voltage, resistance):
    """Return the current in milliamps through a resistor (Ohm's law)."""
    return voltage / resistance * 1000

print(current_ma(9.0, 450.0))           # 20.0
print(f"{current_ma(5.0, 220.0):.1f}")  # 22.7

The text in triple quotes is a docstring, describing what the function does. Functions make programs easier to read (a good name explains intent), easier to test (you can check one function on its own), and easier to fix (a correction in one place applies everywhere it is used).

Here are two functions that work together to clean up a list of readings:

def average(values):
    return sum(values) / len(values)

def keep_in_range(values, low, high):
    kept = []
    for v in values:
        if low <= v <= high:
            kept.append(v)
    return kept

readings = [12.1, 12.3, 55.0, 12.2, 12.4]
clean = keep_in_range(readings, 0, 50)

print(f"All readings: {average(readings):.2f}")   # 20.80
print(f"In range:     {average(clean):.2f}")      # 12.25

One bad reading pulled the average from about 12 to nearly 21. Filtering helps — but think carefully before discarding data. The 55.0 might be a sensor glitch, or it might be a real event you need to know about. Removing values should be a deliberate, documented decision, never a quiet way to get a nicer number.

A first simulation: cooling tea

Many physical processes can be simulated by asking: given the state now, what will it be a moment later? — and repeating. This is called stepping forward in time.

A hot drink cools faster when it is much hotter than the room, and more slowly as it approaches room temperature. A simple model, known as Newton's law of cooling, says the rate of cooling is proportional to the temperature difference. Over a small time step, the drop in temperature is roughly:

drop = k · (T − T_room) · dt

where k is a cooling constant that depends on the cup, and dt is the length of the step. In Python:

temperature = 90.0   # °C, starting temperature
room = 20.0          # °C
k = 0.1              # cooling constant, per minute (an assumed value)
dt = 1.0             # time step, minutes

for minute in range(1, 11):
    temperature = temperature - k * (temperature - room) * dt
    print(f"t = {minute:2d} min   T = {temperature:5.1f} °C")

Output:

t =  1 min   T =  83.0 °C
t =  2 min   T =  76.7 °C
t =  3 min   T =  71.0 °C
t =  4 min   T =  65.9 °C
t =  5 min   T =  61.3 °C
t =  6 min   T =  57.2 °C
t =  7 min   T =  53.5 °C
t =  8 min   T =  50.1 °C
t =  9 min   T =  47.1 °C
t = 10 min   T =  44.4 °C

The drops get smaller as the tea approaches room temperature, which matches everyday experience. Notice the shape of this code: it is the same "next = now + change" pattern as the feedback controller in Robotics Foundations. Stepping a model forward in time is one of the most important ideas in computational engineering.

Step size matters

Let us wrap the simulation in a function and ask how long the tea takes to cool to 60 °C:

def minutes_to_cool(start, room, k, target, dt):
    t = 0.0
    temp = start
    while temp > target:
        temp = temp - k * (temp - room) * dt
        t += dt
    return t

print(round(minutes_to_cool(90.0, 20.0, 0.1, 60.0, dt=1.0), 2))   # 6.0
print(round(minutes_to_cool(90.0, 20.0, 0.1, 60.0, dt=0.1), 2))   # 5.6

The two answers differ. With one-minute steps, the simulation can only report whole minutes and assumes the cooling rate stays fixed for a whole minute. Smaller steps follow the true curve more closely; for this model, the exact answer is about 5.6 minutes. Choosing a step size small enough to be accurate but large enough to run quickly is a decision every simulation engineer makes — and a result is not trustworthy until you have checked that making the step smaller does not change it much.

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

Knowledge check

Check your understanding

  1. 1. Which numbers does range(4) produce?
  2. 2. What decides which lines belong inside an if block in Python?
  3. 3. temperature = 25. Which line is printed by: if temperature > 30: ... elif temperature > 20: print("warm") else: print("cool")?
  4. 4. Why might a while loop run forever?
  5. 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?

Go further

Sign in to track your progress. Reading is free without an account.