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

时间:2019-04-28 08:03:11

标签: python function

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")

应该运行代码,并且如果决策三的输入不是Yes或No,则用户应该重新输入输入。每当我运行代码时,它都会无限地询问Decision3。

1 个答案:

答案 0 :(得分:3)

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()的返回值强制转换为字符串。已经是一个了。