我知道这段代码还有其他问题,但我想知道为什么try语句一直停留在循环中。我在退还salesPrice后放了一个中断声明。我也试着在退还salesPrice之前放了中断声明,但它不起作用。为什么它没有用break语句跳出循环?
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()
一些问题:
-
函数
getFloatInput
一次又一次地调用自己,没有任何条件。它没有理由调用自己,因为您已经有了一个允许重复提示的循环。 -
return
语句正下方的代码永远无法到达 -
getFloatInput
从不使用sales
参数。这是一个不必要的参数。 -
主代码将在
if
块中第二次调用getFloatInput
,但该值随后被忽略——它不会添加到列表中。不应在那里调用getFloatInput
。循环应该只是在它将被调用的地方进行下一次迭代。 -
i
名称过于夸张。你可以做while True:
。 -
循环体末尾的
continue
没有任何用处——当执行到达该点时,循环无论如何都会继续。
这是一个更正的版本:
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()
您正在函数本身的salesPrice = getFloatInput(float(input("Enter a property sales values: ")))
行调用getFloatInput(sales)
函数。您的代码实际上并没有到达return salesPrice
行,因为您正在再次调用该函数。