Round up to the nearest pound.

Save the change

⭐⭐⭐

Try

Select the button below to open the Python program in a new window. Run the program and read the lines of code to see if you can understand how it works. It will be helpful to arrange your display so that you can have this browser window on one side of the screen and the code on the other.

Watch this video to learn about the new concepts shown in the program:

Knowledge organiser

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.

Investigate

Questions to think about with this program to check your understanding:

Purpose question

Explain the purpose of using int in line 7 to cast the variable amount from a float to an integer.

Reveal answer

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.

Reason question

Why has the format method been used in line 24?

Reveal answer

To make the output of debit two decimal places. The format method provides for the formatting of strings for output.

Make

Change the program so that it:

  1. Does not output the debit of an additional pound if the purchase price is whole pounds. E.g. If the purchase price is £3, it should not debit £4.
  2. Outputs the credit to savings to be £0.00 if the purchase price cannot be rounded up.

Typical inputs and outputs from the program would be:

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