fb pixel

Arithmetic operations

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 + 2 is executed as a = 10 + 2 and therefore, 12 is assigned to a and the previous value is forgotten. The expression a = a + 2 can be simplified into a += 2 which means exactly the same - add 2 to a and assign the new value to a.
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:
Operator
Shorthand
Expression
Description
+=
x += y
x = x + y
Add y to x and assign the resulting value to x
-=
x -= y
x = x - y
Subtract y from x and assign the resulting value to x
*=
x *= y
x = x * y
Multiply x by y and assign the resulting value to x
/=
x /= y
x = x / y
Divide x by y and assign the resulting value to x
%=
x %= y
x = x % y
Compute the remainder of dividing x by y and assign the resulting value to x
**=
x **= y
x = x ** y
Exponentiate x by y and assign the resulting value to x
//=
x //= y
x = x // y
Compute floor division of x and y and assign the resulting value to x

Challenge

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.
Input
Output
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 total and assign 0 to it at the beginning. After an item is added to the basket, you can add the number to the total variable and print it.
 
To check your solution you need to sign in
Sign in to continue