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

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

Add the sales tax to the subtotal for the final total


total = subtotal + sales_tax


Show the user the total amount due, including tax


print("The total cost is $",total)
print("This includes $", subtotal, "for the pizza and")
print("$", sales_tax, "in sales tax.")


This program combines what you’ve learned about variables
and operators into a single powerful program. Read through
it and make sure you understand how each part works. How
would you change the program to make it work for a different
rate of sales tax?
Notice that we have included the steps of our program as
comments, using the # (hash mark). Remember that comments are
there for humans to read; the IDLE editor colors comments red
to remind us that Python will ignore those parts. This practice of
spelling out our programs step by step in words first, then putting
those steps into our program as comments, can be very helpful as
we build longer and more complex programs. This is our algorithm,
the set of steps to be followed in our program. Algorithms are like
recipes: if we follow all the steps in the right order, our program
turns out great!
When we write our algorithm
in words (as # comments) and in
code (as programming statements),
we’re accomplishing two goals.
First, we’re reducing errors in our
program by making sure we don’t
leave out steps. Second, we’re mak-
ing our program easier for us and
others to read and understand
later. You should get in the habit
of writing clear comments in your
programs from the very beginning,
and we’ll do this often throughout
the book. If you don’t want to type
all of the comments, the program
will still run; they’re just there to
help you understand what the pro-
gram is doing.

Free download pdf