I know there are other issues with this code but I am wondering why the try statement stays stuck in the loop. I put a break statement after I return the salesPrice I also tried putting the break before I returned the salesPrice and it does not work. Why isnt it breaking out of the loop with the break statement?
def getFloatInput(sales):
i = True
while i:
try:
salesPrice = getFloatInput(float(input("Enter property sales value: ")))
return salesPrice
break
if salesPrice <= 0:
print("Enter a numeric value greater than 0")
except ValueError:
print("Input must be a numeric value")
continue
def main():
sales = float(input("Enter property sales value: "))
addToList = []
i = True
while i:
addToList.append(getFloatInput(sales))
repeat = input("Enter another value Y or N: ")
if repeat == "Y":
getFloatInput(sales)
else:
break
main()
>Solution :
Some of the issues:
-
The function
getFloatInputcalls itself over and over again, without any condition. There is no reason for it to call itself, since you already have a loop that allows for repeating the prompt. -
The code that follows immediately below the
returnstatement can never be reached -
The
salesargument is never used bygetFloatInput. It is an unnecessary parameter. -
The main code will call
getFloatInputa second time in theifblock, but that value is then ignored — it is not added to the list.getFloatInputshould not be called there. The loop should just make its next iteration where it will be called. -
The
iname is overkill. You can just dowhile True:. -
continueat the end of a loop body has no use — the loop will anyhow continue when execution gets at that point.
Here is a corrected version:
def getFloatInput():
while True:
try:
salesPrice = float(input("Enter property sales value: "))
if salesPrice > 0:
return salesPrice
print("Enter a numeric value greater than 0")
except ValueError:
print("Input must be a numeric value")
def main():
addToList = []
while True:
addToList.append(getFloatInput())
repeat = input("Enter another value Y or N: ")
if repeat != "Y":
break
main()