Introduction to Python Resources

Begin your free Python journey now,
at your own pace

check

Practice: Float Operators

check

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

  1. Define a variable named soup_can_cost, and assign it the value 2.95.
  2. Define a variable named soup_can_qty, and assign it the value 8.0.
  3. Define a variable named soda_pack_cost, and assign it the value 13.84.
  4. Define a variable named soda_pack_qty, and assign it the value 2.0.
  5. Define a variable named sales_tax_percent, and assign it the value 7.75.
  6. 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.
  7. Print the value contained in the transaction_cost variable.
  8. Define a variable named cash_in_wallet, and assign it the value 87.25.
  9. Define a variable named cash_remaining, and using the variables above, assign it your initial cash minus the cost of the transaction.
  10. Print the value contained in the cash_remaining variable.
HINT*: Click here for a hint
*Hints are best viewed after completing a task, or after spending some time and effort attempting it. In cases where a hint contains example output, it is important to understand why it is correct, as there may be many correct outputs.

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
*Example solutions are best viewed after completing a task and understanding the outcome. In most cases, there are multiple ways to complete a task, and the example solution is only one example.
  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