Working with Numbers

Learn about how can we use numbers in computer programs.

The importance of numbers

Numbers are essential in computer programs. We use them to represent real-world concepts, such as the number of items in a shopping cart, the weight of a package, and the distance to a location. We also use them to represent internal things within our program, such as the number of characters in a name, so that we can calculate whether it will fit on an address label if we print it. The point is, we use numbers all the time, so let’s see what we can do with them.

Performing arithmetic operations

First, we can do basic arithmetic, such as addition, subtraction, and division, as in the following code snippet:

Note: The output of the code below will be an integer because integer division is taking place.

Press + to interact
age1 = 34
age2 = 67
medianAge = (age1 + age2) / 2
print medianAge

In this example, we have two ages and we’re calculating the median age. We often use numbers as counters of things. What this means is that we’ll use them to keep track of how many times we’ve done something. This means that we need to increase (and sometimes decrease) them by 1. We could do this as follows:

count = count + 1

To understand what’s happening here, we need to look to the right of the = sign first. Here, we have a variable called count. Because this is just a line that has been pulled out of its context, we can assume that it already has a value stored. This value is now used, and we add 1 to it. The result of this addition is then stored back in the variable count, ...