【问题标题】:Python - Never Ending While Loops caused by a DefinitionPython - 由定义引起的永无止境的 While 循环
【发布时间】:2021-08-20 15:32:34
【问题描述】:

我目前正在为我的评分系统制作一个主菜单,通过使用 while 循环作为一种简单的验证形式,将用户带到代码的不同部分,但它会导致一个永无止境的 while 循环,因为我的一些定义也有while 循环也是如此。这就是我所做的

def menu():
 print("""\n Main Menu \n
 1) Join the Event as a Team
 2) Join the Event by Yourself
 3) Score Screen""")

 menuchoice_option = ["1","2","3"]

 menuchoice = ""

 while menuchoice not in menuchoice_option:
  menuchoice = input("Please enter your choice here:")

 if menuchoice == "1":
  team_menu()
  menuchoice = True
 elif menuchoice == "2":
  individual()
  menuchoice = True
 elif menuchoice == "3":
   #scorescreen()
   menuchoice = True
 else:
   menuchoice = False
   print("Please enter a value between 1-3")
   menuchoice = input("Please enter your choice here:")

这是菜单 def 导致执行无限循环的其他功能

def team_menu():

 global teamS
 team_player = ""
 while team_player != "":
  team_player = input("What is your name:")
  print("""\n Available Teams \n
  1) Team Ahab
  2) Team Ishmael
 \n 3) Go back to Main Menu\n""")

 team_choice = ""
 team_choice_option = ["1","2","3"] # all valid choices on team menu

 while team_choice not in team_choice_option:
  team_choice = input("Enter your choice here:")

 if team_choice == "1":
  teamS["Team 1"]["Team Ahab"].append(team_player)
  print(teamS["Team 1"])
  print("Thank You for Joining Team Ahab")
  team_choice = True

 elif team_choice == "2":
 teamS["Team "+ team_choice]["Teeam Ishmael"].append(team_player)
 print(teamS["Team 2"])
 print("\nThank You for Joining Team Miller\n")
 team_choice = False

elif team_choice == "3":
 menu()
 team_choice = True

else:
 print("Enter a value between 1-3")
 team_choice = False

我的理想输出是它停止在我的代码中导致来自不同定义的无限 while 循环。我是初学者,请执行我

【问题讨论】:

  • 我们还必须查看您的导致无限循环提供帮助的函数
  • 你的menuchoice是用户输入的字符串;然后你用menuchoice = True 覆盖它。不知道这背后的想法是什么。
  • 如果你在team_menuindividual 中再次调用menu(),你就做错了。
  • 您是在 Python 3 还是 Python 2 解释器中运行代码?如果您在输入提示符下键入"1"(带引号)会发生什么? input() 函数在 Python 2 中的工作方式非常不同。我只能使用 Python 2 解释器重现您的问题。
  • 对布尔值使用不同的变量

标签: python function while-loop boolean


【解决方案1】:

旧:

嗯...True 永远不会是您的menuchoice_option 之一,他们是1,2,3。 制作menuchoice="1"(而不是True),例如,如果用户选择"1"

编辑

尝试简化您的代码:理想情况下,数据应该是原子的,并且代码应该围绕数据工作以尽可能地提取和发挥最佳/智能。并使用更好的缩进(有助于查看块)。 像下面这样的东西维护/开发会好得多:

def menu():
  options = {
    1: "Join the Event as a Team",
    2: "Join the Event by Yourself",
    3: "Score Screen"
  }

  funcs = {
    1: team_menu,
    2: individual,
    3: scorescreen
  }

  print("\n Main Menu \n")
  for k,v in options.items():
    print(f"{k}) {v}")

  choice = None
  while choice not in options:
    # notice that if a value invalid for "int()" casting, 
    # the code will blow. Wrap this with try/except to avoid it.
    choice = int(input("Please enter your choice here:"))

  # By now, you know a valid option was chosen.
  # Let's use to select the corresponding function from "funcs" dict
  funcs[choice]()

我没有测试它。但看起来工作正常。

【讨论】:

  • 虽然这是个好主意,但它不会停止无限循环问题,因为while 循环发生在之前 menuchoice 被分配一个布尔值。
  • @jjramsey 对...现在仔细看,我实际上不知道无限循环是从哪里来的。除非他在某个子函数中调用menu,否则在while 超过之后我看不到循环......无论如何,就是这样,我在这里给了我的 2 美分。希望我能帮助某人改进他们的 Python 代码。谢谢。
  • 对不起,解释不好,但我所说的无限循环是指在我使用 while 循环完成一个 def 之后,它会引导我使用 while 循环进入另一个 def,因此解释了我所说的“无限循环”的含义" @jjramsey
  • @Brandt 尝试了您的代码,它成功了!谢谢那个男人! for k,v in options.items(): print(f"{k}) {v}") 到底是做什么的?
  • 好@PaulAtreidis,我很高兴它有帮助。如果您认为这是对您的问题的“正确答案”,请这样做。要理解这些行,请查看 Python 字典 items() 方法,并(关于 print)查找 Python “F-strings”。
【解决方案2】:

对菜单使用一些递归怎么样,我分享我的想法:

options = """
Main Menu

 1) Join the Event as a Team
 2) Join the Event by Yourself
 3) Score Screen
 4) Exit

>>> """

def menu(menuchoice):
    if menuchoice == "1":
        team_menu()
    elif menuchoice == "2":
        individual()
    elif menuchoice == "3":
        #scorescreen()
        pass
    elif menuchoice == "4":
        exit()
    else:
        print("Please enter a value between 1-5")
        decision = str(input(">>> "))
        menu(decision)



if __name__ == "__main__":
    decision = str(input(options))
    menu(decision)

我希望我能给你一个想法。

【讨论】:

    猜你喜欢
    • 2023-03-22
    • 2019-03-03
    • 1970-01-01
    • 2020-03-14
    • 1970-01-01
    • 1970-01-01
    • 2016-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多