Turning a formula into code: area
If you know a formula, writing the program is easy. The area of a rectangle is length times width. The program has the same three parts as before: read two numbers, calculate, show. In Python the times sign is *, so the formula becomes area = length * width. When the user types 6 and 4, the screen shows 24. A formula with more than one operation needs care. The perimeter of a rectangle is two times the sum of the length and the width. If we forget the brackets and write 2 * length + width, Python multiplies first and gives the wrong answer, as in Week 2. So we write 2 * (length + width). Formulas are everywhere: a price list is also a formula, cost = price * count.
1length = int(input("Length in cm: ")) 2width = int(input("Width in cm: ")) 3area = length * width 4print(area)
Length in cm: 6 Width in cm: 4 24
1length = int(input("Length in cm: ")) 2width = int(input("Width in cm: ")) 3perimeter = 2 * (length + width) 4print(perimeter)
Length in cm: 6 Width in cm: 4 20
1price = 12 2count = 5 3cost = price * count 4print(cost)
60
Write the formula and the Python lines for the area of a square whose side is typed by the user. Then do the same for the cost of a number of pencils at a price you choose. Work out the answer for one test by hand.