There's no point in initializing these variables to zero. Also, by PEP 8, variables should be named like room_width
.
RoomWidth = 0
RoomHeight = 0
RoomTotal = 0
RoomPaint = 0
Python supports double-ended inequalities, so
if ((RoomWidth <=25 and RoomWidth >=1) and (RoomHeight <=6 and RoomHeight >=2)):
can be simplified to
if (1 <= room_width <= 25 and 2 <= room_height <= 6):
However, your code would be easier to read if you get the very short error handler out of the way first:
if (not(1 <= room_width <= 25) or not(2 <= room_height <= 6)):
print("Invalid input")
else:
# Continue calculating
The user would still likely be puzzled by an "Invalid input" message, though, especially if the width is out of range. We could improve the user experience with better input/validation routines.
def prompt_float(prompt, validator=None):
while True:
try:
val = float(input(prompt))
if validator is None or validator(val):
return val
except ValueError:
pass
print("Invalid input")
room_width = prompt_float("Enter the room width, which must be between 1m-25m: ",
lambda val: 1 <= val <= 25)
room_height = prompt_float("Enter the room height, which must be between 2m-6m: ",
lambda val: 2 <= val <= 6)
The program would benefit from further generalization of the prompting routine. Basically, your goal is to translate all user input into some kind of number. In the case of the room dimensions, it was just a matter of interpreting a string as a float
. However, we could also transform the value using lookups.
By generalizing the prompting routine that was developed above, we get input validation everywhere, for free.
def prompt(prompt, validator=lambda val:val is not None, transform=float):
while True:
try:
val = transform(input(prompt))
if validator is None or validator(val):
return val
except ValueError:
pass
print("Invalid input")
room_width = prompt("Enter the room width, which must be between 1m-25m: ",
validator=lambda val: 1 <= val <= 25)
room_height = prompt("Enter the room height, which must be between 2m-6m: ",
validator=lambda val: 2 <= val <= 6)
paint_unit_cost = prompt("Please choose from a selection of paints: 'Luxury', ['Standard'], or 'Economy': ",
transform=lambda val: {
'luxury': 1.45,
'standard': 1.00,
'economy': 0.45,
'': 1.00, # "Standard" is the default
}.get(val.lower()))
undercoat_unit_cost = prompt("Would you like to use an undercoat? Y/N: ",
transform=lambda val: {'y': 0.5, 'n': 0.0}.get(val.lower()))
cost = 4 * room_width * room_height * (paint_unit_cost + undercoat_unit_cost)
print("The total cost of painting this room is £{0:.2f}".format(cost))