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
I’m not going to spell out an answer since it is homework, but I will point you in the right direction. First I suggest using a while loop instead of recursion.
The code might look something like:
Second, the problem you’re having now has everything to do with variable scope. When bad input happens you call the function again, but do nothing with the output.
Remember that the x in the first function call is completely separate from the x in the second function call.
So if you intend to use recursion, you need to figure out how to pass the x value “back up the chain.”