Skip to content

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.

# Constant values, independent of starting parameters

Naming conventions

Python does most things by convention, not by enforcement. 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 (_).

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.

# Simulation starting parameters
starting_population = 118
food_per_day = 20

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.

current_population = starting_population
current_food = food_per_day  # Don't forget to feed them on the first day 

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.

excess_food = current_food - current_population * FOOD_PER_INDIVIDUAL
number_groups = current_population / INDIVIDUALS_PER_GROUP

We can output these calculation results, so we know what has been calculated.

print(current_population, "individuals,", current_food, "food, leaves", excess_food, "food")
print("There are", number_groups, "groups")

Key Points

  • 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
Code Checkpoint

This is the code that we have so far: