Teach Your Kids To Code: A Parent-friendly Guide to Python Programming

(vip2019) #1
Numbers and Variables: Python Does the Math 39

Notice that in the last assignment statement, we used x on
both sides of the equal sign: x = x - 7. In an algebra class, this
would be an invalid statement, since x can never equal x - 7. But
in a program, the computer evaluates the right side of the equation
first, calculating the value of x - 7 before it assigns that value to
the x on the left side. Variables on the right side of the equal sign
get substituted with their values; here, the value of x is 9 , so the
computer plugs 9 into x - 7 to get 9 - 7, which is 2. Finally, the vari-
able on the left side of the equal sign, x, is assigned the result of the
calculation from the right side. The value of x changes only at the
end of the assignment process.
Before we move on to a programming example, let’s go over
one additional feature of math in Python. In Table 3-1 and in
Figures 3-2 and 3-4, we used the division operator—the for-
ward slash (/)—and Python responded with a decimal value. For
4 / 2, Python gave us 2.0, not the 2 that we might expect. This is
because Python uses what it calls true division, which is meant
to be easier to understand and less likely to cause errors.
We see the positive effect of Python’s true division in Figure 3-4
when we ask Python to calculate x / 2, with x equal to 5. Python
tells us that 5 divided by 2 is equal to 2.5, which is the result we
expect. This division is like dividing five pizzas equally between
two teams: each team gets 2.5 pizzas (the result of 5 / 2). In some
programming languages, the division operator returns only the
whole number (that would be 2 in this case). Just remember that
Python does “pizza division.”


Programming with Operators: A Pizza Calculator


Speaking of pizza, now let’s imagine you own a pizzeria.
Let’s write a small program to figure out the total cost of
a simple pizza order, including sales tax. Say we’re ordering
one or more pizzas that all cost the same, and we’re ordering in
Atlanta, Georgia, in the United States. There’s a sales tax that’s
not included in the menu price but is added at the end of the pur-
chase. The rate is 8 percent, meaning that for every dollar we pay
for the pizza, we must also pay eight cents in sales tax. We could
model this program in words as follows:



  1. Ask the person how many pizzas they want.

  2. Ask for the menu cost of each pizza.

Free download pdf