Storing Data in Variables
Variables Make Remembering Easier¶
From our mission statement we can already determine some values that have to go into our program. Instead of repeating the numbers again and again and risking difficult to spot errors and hard to understand code, we could save these values under certain names to enhance them with a bit of meaning.
When we want the computer to remember something we can use a variable to store a certain value under a given variable name.
To achieve this we use a so-called assignment using the assignment operator
There are some fixed values we find in our mission statement already, that we will need in our simulation:
# Constant values, independent of starting parameters
# How many individuals are required to form a group
INDIVIDUALS_PER_GROUP = 7
# Number of individuals that will be born (per group) if excess food is available
GROWTH_PER_GROUP = 3
# Number of individuals that will perish (per group) if food is insufficient
DECLINE_PER_GROUP = 2
# Amount of food (in kg) that each individual requires
FOOD_PER_INDIVIDUAL = 0.25
The conventions for how to name variables are specified in a document known as PEP 8.
According to this specification, variables that hold constant values are written in all upper-case, while variables that hold potentially changing values are written in all lower-case letters.
Words in variable names get connected with an underscore (
To help understand code better, we can add so called comments.
These are parts of the program code that are ignored by the interpreter.
Comments start after a
#-sign and continue until the end of a line.
There are also some other starting parameters to remember for our simulation. We may chose different values for them to simulate a variety of situations.
Usually we want to keep the starting parameters the same during the run of the simulation to reference them later on. Let’s introduce some further variables that can track the food and population as the simulation progresses. These of course are initially the same as the starting values.
To calculate whether a population will grow or shrink (and by how much), we need to know how many groups there are and if we have a food surplus or deficit.
Note that Python will do the calculation on the right side of the
= first and only afterwards will do the assignment.
We can output these calculation results, so we know what has been calculated.
- Variables represent places in the computers (volatile) memory that are used to store values
- The variable name is used to refer to a specific variable
- An assignment is used to store a value in a variable
- If the right side of an assignment is an expression, it will be evaluated first
This is the code that we have so far: