Calculate the cost of a carpet.
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:
x = int(y)Casts (converts) the string y into an integer x. Integers are whole numbers, positive, negative or zero.
x = float(y)Casts (changes) y into a decimal x. Decimals are also called floats or real numbers.
x = input(y)Assigns x to be an input from the keyboard using prompt y.
return xReturns the value x from a subprogram so that it can be used elsewhere in the program.
+ add
- subtract
* multiply
/ divide
,The concatenator , joins strings and variables into a single output. E.g. print("Hello", "World") You can also use + if you don’t want a space between each piece of data.
A comma is also used to separate different items of data.
Questions to think about with this program to check your understanding:
Explain the purpose of the int command in lines 15, 16 and 17.
“int” is a function that converts the input from the keyboard that will always be text, known as a “string” into a whole number, known as an “integer” so that it can be used for mathematical calculations. This is known as “casting”.
Explain why a subprogram was used in lines 6-10 instead of writing the code from line 19 onwards.
Breaking a program down into subprograms is called decomposition. It makes it easier to write different parts of the program a step at a time. It is easier to read the code. It allows a section of code to be resused more easily.
Change the program below so that it:
Enter the width of the room to nearest meter: 2
Enter the length of the room to nearest meter: 3
Enter the price of the carpet per m2: 2
The total cost is: £ 79.0
# Carpet cost program
# -------------------------
# Subprograms
# -------------------------
# Calculate the cost of a carpet
def carpet_cost(width, length, price):
---
carpet = width * length * price
underlay = width * length * 2
---
grippers = width + length
fitting = 50
return carpet + underlay + grippers + fitting
---
# -------------------------
# Main program
# -------------------------
width = int(input("Enter the width of the room to nearest meter: "))
length = int(input("Enter the length of the room to nearest meter: "))
price = float(input("Enter the price of the carpet per m2: "))
print("The total cost is: £", carpet_cost(width, length, price))