here I improved your code:
def pints_to_litres():
over = False
while not over:
try:
pints = int(raw_input("Please enter the amount of Imperial Pints you would like converted into Litres >>>"))
litres = pints * float(0.568261)
print (""+str(pints)+ " Pint(s) is equal to " +str(litres)+ " Litre(s)")
if (pints < 0):
print("Invalid Input! Try Again")
else:
over = True
except ValueError:
print("Invalid Input! Try Again")
- useless setting of
pints
before overwriting it withraw_input
; - changed use of
input
in favor ofraw_input
designed for that purpose ; - if the string is invalid, it throws a
ValueError
at the time of theint()
conversion of pints and loops again ; - if the value is too low, it loops again ;
- As you can see, I also changed your recursive call to the function, as if the user always fails, you'll end up smashing the function stack limit, and have a failure.