Round up to the nearest pound.
Watch this video to learn about the new concepts shown in the program:
The new commands used in this program and others that may be useful. Select them below to learn more:
int(x)Serves two purposes. It casts (converts) data into an integer, but in doing so it also truncates the number so that any decimal part is lost. This results in rounding a number down.
"{x:y}".format(z)Returns the parameter x in the string format defined by y using the variable z.
E.g. Assuming two variables name = “Dave” and age = 18, the following statement:
print("Hello {0}. You are {1} years old.".format(name, age))
will output “Hello Dave. You are 18 years old.”
Note how the numbers inside the curly brackets refer to the order of the parameters in the format function.
.2f
Is a formatting string meaning two decimal places, floating point number.
Questions to think about with this program to check your understanding:
Explain the purpose of using int in line 7 to cast the variable amount from a float to an integer.
To round down the number. When casting from one data type to another, data can be lost. We used this to our advantage in this example because we want to discard the decimal places resulting in the number being rounded down.
Why has the format method been used in line 24?
To make the output of debit two decimal places. The format method provides for the formatting of strings for output.
Change the program so that it:
Enter the purchase price: £3.40
Debit - £4.00
Credit to savings - £0.60
Enter the purchase price: £3
Debit - £3.00
Credit to savings - £0.00
Enter the purchase price: £10.23
Debit - £11.00
Credit to savings - £0.77
# Save the change program
# -------------------------
# Subprograms
# -------------------------
# Return the nearest whole number rounded up
---
def nearest_pound(amount):
---
if int(amount) != amount:
---
nearest = int(amount) + 1
---
else:
---
nearest = int(amount)
---
return nearest
---
# Return the difference between the number and the rounded number
def save_the_change(amount):
---
if int(amount) != amount:
---
savings = nearest_pound(amount) - amount
---
else:
---
savings = 0
---
return savings
---
# -------------------------
# Main program
# -------------------------
---
purchase_price = float(input("Enter the purchase price: £"))
---
debit = nearest_pound(purchase_price)
savings = save_the_change(purchase_price)
---
print("Debit - £{0:.2f}".format(debit))
print("Credit to savings - £{0:.2f}".format(savings))