Values and Variables · practice
Calculate with Variables
An
number_of_items = 4
price_per_item = 3
total = number_of_items * price_per_item
print(total)
Python handles the third line in two steps:
Find the current values of
number_of_itemsandprice_per_item, then multiply them.the result to the variable total.
The name total now refers to the integer 12.
Why not write the answer directly?
You could write total = 12, but then the relationship between the values disappears. If the number of items changes, someone must calculate and replace the total by hand.
With an expression, the program performs the calculation from the current values:
Change number_of_items to 8 and run it again. The expression has not changed, but the result has.
This is one of the main reasons variables matter. They let you describe a general relationship instead of one fixed answer.
The right side uses current values
Python evaluates the right side of an assignment first:
width = 6
height = 4
area = width * height
When Python reaches the third line, width is 6 and height is 4, so area becomes 24.
If width changes later, area does not update by itself:
The output is still 24. Python calculated area when it reached the assignment. To calculate it again with the new width, you would run area = width * height again.
What will this program print?
price = 5
quantity = 3
total = price * quantity
quantity = 4
print(total)See a calculation take shape
In the exercise editor, the four starting variables are assigned before ticket_total. The debugger’s Locals panel shows ticket_total appear only after its assignment runs. The output remains empty until the final print instruction runs.
After you replace 0 with your expression, the same view will show Python store the calculated 45 before it prints it. This separates the calculation from the printing.
Calculate a ticket total
The starter program contains prices and quantities for two kinds of ticket.
Replace 0 in the ticket_total assignment with one expression that calculates:
adult tickets * adult price + child tickets * child price
Use the four existing variable names and the * and + 45.
Do not change the four starting values. The goal is to make the relationship visible in the expression.
If the result surprises you, calculate each ticket type separately on paper, then compare that with the expression you wrote.
Task
Replace 0 with an
Use adult_tickets, child_tickets, adult_price, and child_price. The program should print 45.
Keep the four starting values and print(ticket_total) unchanged. Use * and + in your expression.
Before editing, press Step in the editor toolbar and watch the four starting ticket_total. After replacing 0, step through again and watch ticket_total become 45 before the print instruction produces output.