
Practice: Float Operators
Performing arithmetic with floating-point numbers.
Float Operators in Python
As mentioned briefly in the previous exercise on floats, the arithmetic operators used with integers can also be used with floating-point numbers and result in another float:
- Addition (
+), subtraction (-), and multiplication (*) work the same. - Floor division (
//) and modulus (%) assume division a whole number of times, but still output a float. - Parentheses (
()) are still useable and the order-of-operations is the same.
In this exercise, you will be getting some additional practice using the arithmetic operators with float values.
You are welcome to reference the previous exercises as you work on this one.
Practice: Floating-Point Arithmetic
- Define a variable named
soup_can_cost, and assign it the value2.95. - Define a variable named
soup_can_qty, and assign it the value8.0. - Define a variable named
soda_pack_cost, and assign it the value13.84. - Define a variable named
soda_pack_qty, and assign it the value2.0. - Define a variable named
sales_tax_percent, and assign it the value7.75. - Define a variable named
transaction_cost, and assign it the total cost paid for all shopping list items above, using the variables above. Individual item costs are pre-tax. - Print the value contained in the
transaction_costvariable. - Define a variable named
cash_in_wallet, and assign it the value87.25. - Define a variable named
cash_remaining, and using the variables above, assign it your initial cash minus the cost of the transaction. - Print the value contained in the
cash_remainingvariable.
HINT*: Click here for a hint
You should see the total cost of the groceries, followed by the cash you have left after buying them:
>55.2542 31.9958
SOLUTION*: Click here for an example solution
soup_can_cost = 2.95
soup_can_qty = 8.0
soda_pack_cost = 13.84
soda_pack_qty = 2.0
sales_tax_percent = 7.75
transaction_cost = (1 + sales_tax_percent / 100.0) * (soup_can_cost * soup_can_qty + soda_pack_cost * soda_pack_qty)
print(transaction_cost)
>55.2542
cash_in_wallet = 87.25
cash_remaining = cash_in_wallet - transaction_cost
print(cash_remaining)
>31.9958