为什么我的函数被无限调用


i = 1
while i != 3:
  if i == 1:
    def main3():
      decision3 = str(input("Do you accept? (Yes or No)"))
      if decision3 == 'No':
          print("narration")
      elif decision3 == 'Yes':
          print("narration")
          i = 2
      else:
          print("Sorry, that is an invalid input. Please re-enter.")
          main3()
    main3()
  else:
      i = 3
      print("narration")

它应该运行代码,如果决策三的出局不是"是"或"否",则用户应该重新输入输入。每当我运行代码时,它都会无限地询问 decision3。

i的值永远不会改变,所以main3()被永久调用。

if i == 1:
    def main3():
      decision3 = str(input("Do you accept? (Yes or No)"))
      if decision3 == 'No':
          print("narration")
      elif decision3 == 'Yes':
          print("narration")
          i = 2  # <-- This does nothing to i outside of main3()!
      else:
          print("Sorry, that is an invalid input. Please re-enter.")
          main3()
    main3()  # <-- This is the problem!

i仅在main3()范围内更改,而不是全局更改。

作为旁注,不要将input()的返回转换为字符串。它已经是一个。

最新更新