为什么我的try语句不断重复

  • 本文关键字:语句 try python
  • 更新时间 :
  • 英文 :


我知道这段代码还有其他问题,但我想知道为什么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行,因为您正在再次调用该函数。

最新更新