I'm working on a class project that requires me to obtain a float value from the user. This float value must have exactly two numbers after the decimal in order to be a valid input. This is what I have so far.
while True:
try:
cost = float(input("Enter the price: "))
if cost % 1 == 0:
print("Invalid input for price.")
else:
if cost > 0:
return cost
except ValueError:
print("Invalid input for price.")
Comparing cost % 1
to 0
rules out ints and floats ending in .00, but I'm not sure how I could restrict the accepted input to a float with exactly 2 numbers after the decimal (i.e. x.xx). Also I believe I would need to accept a float like 5.00 so my method isn't going to cut it. I've tried converting cost
to a str and setting restrictions on the length, but that still leaves it open to mistakes. Any advice?