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()
You are calling your getFloatInput(sales)
function within the function itself, on the line salesPrice = getFloatInput(float(input("Enter a property sales values: ")))
. Your code isn't actually reaching your return salesPrice
line because you are calling the function again.
Some of the issues:
The function getFloatInput
calls 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 return
statement can never be reached
The sales
argument is never used by getFloatInput
. It is an unnecessary parameter.
The main code will call getFloatInput
a second time in the if
block, but that value is then ignored -- it is not added to the list. getFloatInput
should not be called there. The loop should just make its next iteration where it will be called.
The i
name is overkill. You can just do while True:
.
continue
at 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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.