I'm trying to control input to allow only greater than 0 numbers, but upon testing this block of text, if I enter an illegal character first (a string, 0 or negative number), receive the error output and then input a valid value, it returns the first value I entered instead of the valid one just entered (which then causes the rest of my script to fail due to type mismatch or illogical values). I've tried moving the "return x" around but it does the same thing either way. says "variable x referenced before assignment" in the second case.
def getPrice():
try:
x = float(input("What is the before-tax price of the item?\n"))
if x <= 0:
print("Price cannot be less than or equal to zero.")
getPrice()
return x
except ValueError:
print("Price must be numeric.")
getPrice()
and
def getPrice():
try:
x = float(input("What is the before-tax price of the item?\n"))
if x <= 0:
print("Price cannot be less than or equal to zero.")
getPrice()
except ValueError:
print("Price must be numeric.")
getPrice()
return x
How can I fix this?
Also if you're curious, this is for a school assignment, I've completed the entire program on my own but I just can't figure out how to debug this.
Edit:
I got a working method now:
def getPrice():
while True:
try:
x = float(input("What is the before-tax price of the item?\n"))
except ValueError:
print("Price must be numeric.")
continue
if x <= 0:
print("Price cannot be less than or equal to zero.")
else:
return x
break
and fixed the original code block (but it still uses recursion):
def getPrice():
try:
x = float(input("What is the before-tax price of the item?\n"))
if x <= 0:
print("Price cannot be less than or equal to zero.")
x = getPrice()
except ValueError:
print("Price must be numeric.")
x = getPrice()
return x