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

(vip2019) #1

40 Chapter 3



  1. Calculate the total cost of the pizzas as our subtotal.

  2. Calculate the sales tax owed, at 8 percent of the subtotal.

  3. Add the sales tax to the subtotal for the final total.

  4. Show the user the total amount due, including tax.
    We’ve seen how to ask the user for input. To calculate with
    numbers we’ve entered as input, we need one more function: eval().
    The eval() function evaluates, or figures out the value of, the input
    that we typed. Keyboard input in Python is always received as a
    string of text characters, so we use eval() to turn that input into a
    number. So if we type "20" into our program, eval("20") would give
    us the number value 20 , which we can then use in math formulas
    to calculate new numbers, like the cost of 20 pizzas. The eval()
    function is pretty powerful when it comes to working with num-
    bers in Python.
    Now that we know how to turn user input into numbers that
    we can calculate with, we can convert the numbered steps of our
    program plan into actual code.


Note For each programming example, you can try writing your own pro-
gram first, before you look at the code in the book. Start by writing
comments (#) outlining the steps you’ll need to solve the problem.
Then fill in the programming steps below each comment, checking
the code in the book when you need a hint.

Type this into a new window and save it as AtlantaPizza.py.

AtlantaPizza.py

# AtlantaPizza.py - a simple pizza cost calculator

# Ask the person how many pizzas they want, get the number with eval()
number_of_pizzas = eval(input("How many pizzas do you want? "))

# Ask for the menu cost of each pizza
cost_per_pizza = eval(input("How much does each pizza cost? "))

# Calculate the total cost of the pizzas as our subtotal
subtotal = number_of_pizzas * cost_per_pizza

# Calculate the sales tax owed, at 8% of the subtotal
tax_rate = 0.08 # Store 8% as the decimal value 0.08
sales_tax = subtotal * tax_rate
Free download pdf