We have seen arithmetic operations and assignments in python. Python provides utility assignments that modify the initial variable itself:
a = 10 # a = 10 b = 2 # b = 2 a = a + 2 # a = 12 b = b + 1 # b = 3 a = a * b # a = 36 print(a, b) # prints 36 3
a = 10 # a = 10 b = 2 # b = 2 a += 2 # a = 12 b += 1 # b = 3 a *= b # a = 36 print(a, b) # prints 36 3
It’s possible to modify the same variable by assigning a new value to itself. Here
a = a + 2is executed as
a = 10 + 2and therefore,
12is assigned to
aand the previous value is forgotten. The expression
a = a + 2can be simplified into
a += 2which means exactly the same - add
aand assign the new value to
The above two code snippets perform exactly the same actions. The ones on the right are shorthands for operations on the left. Below is the list of assignment operations available in python:
Compute the remainder of dividing
Compute floor division of
When doing grocery shopping, it’s important to keep track of the total amount spent. Yet, it’s not always convenient to do so by memorizing. So, you’ve decided to write a program to automate that process and keep track of the total sum after each product is added to the basket.
Write a program that would print the sum of the whole purchase every time an item is added to the basket.
The input contains 10 lines (5 products). For each product, the first line is the name of the product and the second line is its price.
After each input, the program should print
TOTAL:followed by the total amount in the basket.
Noodle 10 Chicken 20 Matches 3 Toys 200 Lamp 40
TOTAL: 10 TOTAL: 30 TOTAL: 33 TOTAL: 233 TOTAL: 273
Tip: You can store a variable called
0to it at the beginning. After an item is added to the basket, you can add the number to the
totalvariable and print it.