您可以在num_rooms范围内循环,将宽度和高度放在一起:from operator import mul
from itertools import count
prem_rate = 3.66
disc_rate = 1.83
while True:
try:
num_rooms = int(raw_input("How many rooms are you looking to carpet? "))
break
except ValueError:
print("Please enter a number")
# use for dict keys for each room
cn = count(1)
room_measurements = {}
# validate and confirm input making sure we get a valid measurement for each room
while len(room_measurements) != num_rooms:
print(room_measurements)
try:
m = map(int, raw_input("Enter length and width of room separated by a space i.e 12 10? ").split())
# user entered something like 1010
if len(m) != 2:
print("Input must be in format width height")
continue
# make sure user is happy with sizes the entered
confirm = raw_input("You entered width {} and height {}\n Press y to confirm or any key to try again".format(*m))
if confirm.lower() != "y":
continue
room_measurements["room {}".format(next(cn))] = m
# catch when user enters input that cannot be cast to int
except ValueError:
print("Invalid input")
# set disc_room to False initially
disc_room = False
if len(room_measurements) > 2:
mn_size = min(room_measurements, key=lambda x: mul(*room_measurements[x]))
disc_room = room_measurements[mn_size]
# remove room so we can calculate separately later
del room_measurements[mn_size]
# if we get three or more rooms if disc_room will evaluate to True
# so calculate prem rate for larger rooms and add discounted room cost
if disc_room:
total = sum(mul(*x) * prem_rate for x in room_measurements.itervalues()) + (mul(*disc_room) * disc_rate)
print(total)
else:
# else less than 3 rooms so just calculate prem rate
total = sum(mul(*x) * prem_rate for x in room_measurements.itervalues())
处理金钱时,您可能需要查看decimal模块。在