所以,我的选择4似乎有问题。我希望它返回主菜单,主菜单可以由main()调用。 "是"显然有效,在输入"是"或"是"以外的任何内容时,应将其返回主菜单。输入" no"或者" hhh"只是退出程序以及"是" /"是"。它也显示相同的"感谢您的演奏"消息好像是"是"。我是Python的初学者,所以请耐心等待。
while endProgram == "Yes" or "yes":
#Selection menu, user input to navigate.
selection = eval(input("Your selection: "))
#Selection 1, rules.
if selection == 1:
rpsRules()
returnMain = input("\nWhen you would like to return to the Main Menu, press Enter.")
main()
#Selection 2, begin a match against the PC, calls againstPC module with choice as an argument.
elif selection == 2:
againstPC(choice)
#Selection 3, begin a match against another player locally, calls twoPlayer module.
elif selection == 3:
twoPlayer()
#Selection 4, end program, with an "Are you sure?" catch.
elif selection == 4:
endProgram = input("\nAre you sure you want to quit? (Yes/No) ")
if endProgram == "Yes" or "yes":
print("\nThanks for playing Rock, Paper, Scissors!\nSee you next time!")
break
elif endProgram == "No" or "no":
main()
else:
main()
elif selection == 5:
creatorCredits()
答案 0 :(得分:1)
这一行:
while endProgram == "Yes" or "yes"
当你用英语读出来的时候,Doe并不意味着它的意思;你需要修改它,以便检查endProgram
的两个值,如下所示:
while endProgram == "Yes" or endProgram == "yes"
然后你可以通过说:
进一步简化while endProgram.lower() == "yes"
您永远不应该在用户输入上使用eval
。这不仅是危险的,也是错误的重要来源,它可能会在您的应用程序中造成不可预测的行为。
事实上,您应该将此逻辑放在您打印菜单的main()
方法中:
def main():
# print the menu here
selection = input("Your selection: ")
try:
selection = int(selection)
except ValueError:
print('Please enter a valid number')
get_user_input()
return selection
然后,在主要时间调用它:
while endProgram.lower() == "yes":
selection = main()
您接下来的问题是本节,它与您的while循环进行相同的检查;这是不必要的。
elif selection == 4:
endProgram = input("\nAre you sure you want to quit? (Yes/No) ")
if endProgram == "Yes" or "yes":
print("\nThanks for playing Rock, Paper, Scissors!\nSee you next time!")
break
elif endProgram == "No" or "no":
main()
else:
main()
要清除所有这些,请按以下方式构建程序:
由于主菜单功能返回有效的响应;您也可以在那里移动退出逻辑:
def main():
# print your menu here
selection = input('Please enter your choice: ')
try:
selection = int(selection)
except ValueError:
print('Sorry, {} is not a valid choice'.format(selection))
main()
if selection == 4:
exit_check = input('Are you sure you want to exit? Type Yes: ')
return exit_check.lower()
if 0 < selection < 4:
print('{} is not a valid menu item.')
main()
return selection
现在,你的程序的主要逻辑循环是这样的:
end_program = main()
while end_program != 'yes':
if end_program == 1:
# do stuff
end_program = main()
if end_program == 2:
# do stuff
end_program = main()
print('Thank you, for playing. Good bye!')
答案 1 :(得分:0)
答案是将您的IF语句更改为:
if endProgram == "Yes" or endProgram == "yes":
...