livepython.net

148. Python Program to Replace Repeated Code with a Function

MediumClean code

Overview

Copying the same lines three times is a sign that they want to be a function. Write it once, call it three times.

Problem Statement

The starter code reads three rooms, one per line, as a name, a length and a width. It prints the area of each room and the total. For example, for Kitchen 3 4, Bedroom 4 5 and Hall 5 6:

Kitchen: 12 square metres
Bedroom: 20 square metres
Hall: 30 square metres
Total: 62 square metres

Rewrite it so that:

  • one function with a clear snake_case verb name does the work for one room: it reads the line, prints the room's area and returns the area,
  • the function has a docstring that says what it does,
  • the main program calls it three times and prints the total,
  • the code follows PEP 8 spacing: spaces around operators, after commas, and two blank lines around the function.

Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.

The tests check only the output, and the starter code already prints it. So they can't see whether you removed the repetition: check that the area is worked out in only one place.

Input

One room per line: a name, a length and a width, separated by spaces. Example:

Kitchen 3 4
Bedroom 4 5
Hall 5 6

Output

The output for that example:

Kitchen: 12 square metres
Bedroom: 20 square metres
Hall: 30 square metres
Total: 62 square metres

The tests try 3 different inputs.

Learn this firstChapter 16 · Clean Code in Python: Habits Every Beginner Needs
solution.py
room=input().split()
a1=int(room[1])*int(room[2])
print(room[0]+":",a1,"square metres")
room=input().split()
a2=int(room[1])*int(room[2])
print(room[0]+":",a2,"square metres")
room=input().split()
a3=int(room[1])*int(room[2])
print(room[0]+":",a3,"square metres")
print("Total:",a1+a2+a3,"square metres")

EXPECTED OUTPUT

1Kitchen: 12 square metres
2Bedroom: 20 square metres
3Hall: 30 square metres
4Total: 62 square metres

YOUR OUTPUT

Press Run to see your output here. Lines are compared with the expected output.