Skip to content
Study Hall
Lesson 5 of 6STEM Skills & Investigations
Unit 1 · Lesson 5 of 6

Coding to Model Science

How a few lines of Python can model science: variables that store measurements, arithmetic and print, for loops that apply a rule over and over, and simple models of a growing population and a cooling cup of tea. You will learn to read a program's output and to judge where a model matches reality and where it does not.

5 min read10 practice questionsInteractiveAsk AI about this →

Key things to remember

  1. 1A variable stores a value; the = sign assigns a value to it.
  2. 2A for loop repeats the indented lines; range(1, 6) gives 1, 2, 3, 4, 5 (it stops before the second number).
  3. 3Growing by r% each step means multiplying by each step (10% growth: multiply by 1.1).
  4. 4Mean = sum of the values ÷ number of values; in Python, sum(values) / len(values).
  5. 5A model is a simplified version of reality; check it against real data and improve it.

Weather forecasts, climate projections and predictions of how a disease spreads all come from computer models. A model is a simplified version of something real that helps you understand it or predict what it will do. A computer model is a set of rules written as code: start with some measured values, apply a rule (such as "the population grows by 10% each year"), and repeat. Computers can repeat a rule millions of times in a second, so scientists can ask "what if?" and see the answer right away. In this lesson you will read and write short Python programs that model science, using the same coding ideas as in math class.

Variables, arithmetic and print

A variable is a name that stores a value, like a labelled box. The line mass = 54.0 means "put 54.0 in the box called mass"; the = sign assigns a value, it does not mean "equals" as in math. Python does arithmetic with + (add), - (subtract), * (multiply) and / (divide). The print function shows values on the screen; text in quotation marks is printed exactly as written. Anything after a # symbol is a comment: a note for people that Python ignores. In the programs below, the comments at the end show the exact output.

mass = 54.0      # grams
volume = 20.0    # cubic centimetres
density = mass / volume
print("Density:", density, "g/cm3")

# Output:
# Density: 2.7 g/cm3
Calculating density from two measurements. The computer works out mass ÷ volume and stores the answer in a new variable.

Loops repeat a rule

A for loop repeats the indented lines below it. It can run once for each item in a list (values in square brackets, separated by commas), or once for each number in a range. range(1, 6) gives the numbers 1, 2, 3, 4 and 5: it starts at the first number and stops before the second. The lines that belong to the loop must be indented (pushed in, usually by 4 spaces). Lines that are not indented run once, after the loop has finished.

readings = [12, 15, 20, 25]   # temperatures in degrees C
for c in readings:
    f = c * 9 / 5 + 32
    print(c, "C =", f, "F")

# Output:
# 12 C = 53.6 F
# 15 C = 59.0 F
# 20 C = 68.0 F
# 25 C = 77.0 F
Converting a list of Celsius readings to Fahrenheit. The loop runs once for each reading; dividing with / always gives a decimal, so 59 prints as 59.0.

A model of a growing population

Suppose 200 rabbits live in a field and the population grows by 10% each year. Growing by 10% means the new population is 100% + 10% = 110% of the old one, so each year you multiply by 1.1. The program below applies that rule five times. round() rounds to the nearest whole number, because you cannot have part of a rabbit. Notice that the increase gets bigger each year (20, then 22, then about 24), because 10% of a bigger number is bigger. This is called exponential growth.

population = 200
for year in range(1, 6):
    population = population * 1.1
    print(year, round(population))

# Output:
# 1 220
# 2 242
# 3 266
# 4 293
# 5 322
A population model: each pass through the loop is one year, and the rule multiplies the population by 1.1 (a 10% increase).
Loading interactive…
Python Tracer: step through short Python programs one line at a time and watch each variable's value change. Try Evaluate a formula (a Celsius to Fahrenheit conversion), Running total and Adding vs multiplying, which use the same skills as the science models in this lesson.

Modelling cooling and analysing data

tea = 90.0    # starting temperature of the tea, degrees C
room = 20.0   # room temperature, degrees C
for minute in range(1, 6):
    tea = tea - 0.1 * (tea - room)
    print(minute, round(tea, 1))

# Output:
# 1 83.0
# 2 76.7
# 3 71.0
# 4 65.9
# 5 61.3
A cooling model: each minute the tea loses one tenth of the difference between its temperature and the room's, so it cools fast at first and then more slowly. round(tea, 1) rounds to one decimal place.
trials = [41.2, 39.8, 40.5, 42.1, 40.9]   # seconds
total = 0
for t in trials:
    total = total + t
mean = total / len(trials)
print("Mean:", round(mean, 2), "s")

# Output:
# Mean: 40.9 s
Finding the mean of five trials. total starts at 0 and the loop adds each trial; len(trials) counts the items (5). The last two lines are not indented, so they run once, after the loop.
Every model is a simplification
The rabbit model says the population grows by 10% forever, but real rabbits run out of food and space, and predators and disease get in the way. The cooling model ignores things like stirring and the shape of the cup. A model is only as good as its rule and its starting values. Scientists test a model by comparing its output with real measurements, then improve the rule when they do not match, just like iterating a design.

Worked examples

Reveal one step at a time and try to beat it to the next line.

Example 1
Trace the population program by hand for the first three years. The population starts at 200 and is multiplied by 1.1 each year. What does it print for years 1 to 3?
Example 2
Bacteria in a dish double every 20 minutes. Write a Python program that starts with 100 bacteria and prints the number after each 20-minute step for 2 hours. What is the last line of output?
Example 3
A student wants the mean of four drop times, but this program prints four numbers instead of one. Find and fix the bug.total = 0 for t in [2.4, 2.6, 2.3, 2.5]: total = total + t print(total / 4)

Where marks get lost

  • Reading = as "equals". In Python, = assigns: count = count * 2 means "replace count with double its old value".
  • Thinking range(1, 5) includes 5. It stops before the second number, so it gives 1, 2, 3, 4 (four passes).
  • Indenting a line that should run once (such as the final print) so it runs on every pass of the loop.
  • Modelling 10% growth by multiplying by 0.1 or adding 10. Growing by 10% means multiplying by 1.1.
  • Trusting a model's output without comparing it with real measurements.

Flashcards 8

Model (in science)
Variable (in code)
for loop
range(1, 6)
+ 4 more

Practice

1
What does this program print?count = 50 for day in range(1, 4): count = count * 2 print(count)
2
How many times does a loop that starts with for year in range(1, 6): run?
3
A model uses the line fish = fish * 1.03 inside a yearly loop. What does it assume about the fish population?
4
What does this program print? Give the number as Python shows it.tea = 80.0 room = 20.0 tea = tea - 0.1 * (tea - room) print(tea)
5
In Python, which symbol starts a comment that the computer ignores?
6
What does this program print?times = [12.0, 14.0, 13.0, 15.0] mean = sum(times) / len(times) print(mean)
7
A student wants a population model to print 5 years, but it prints only years 1 to 4. The loop line is for year in range(1, 5):. What is the fix?
8
Put these steps for building and checking a computer model in order.
  1. 1Improve the rule if the output does not match the data
  2. 2Compare the output with real measurements
  3. 3Use a loop to apply the rule step by step and print the results
  4. 4Decide what quantity to model and the rule for how it changes
  5. 5Store the starting values in variables
9
A rabbit model multiplies the population by 1.1 every year. Why will it eventually stop matching a real rabbit population?
10
Match each coding term to its meaning.
Variable
Loop
List
Comment
Output

Spot a mistake on this page? Let us know