【发布时间】:2019-06-08 00:23:19
【问题描述】:
我目前正在尝试构建一个非常简单的程序,在该程序中要求用户选择路径并根据选择的路径来更新字典。似乎当用户首先选择 path_2b 时,它继续前进并打印“恭喜完成游戏”并停止运行,即使只有 path_2b 已添加到字典中,但它应该只在两条路径都存在时才停止运行。我只是开始学习 Python 的基本知识和一般的编程知识,因此感谢您提供任何帮助和提示!
user_save = {}
def start_button():
def path_2a():
if "path_1" in user_save:
print("You've already taken this path.")
else:
user_save["path_1"] = "completed"
print("Congrats on finishing this path!")
def path_2b():
if "path_2" in user_save:
print("You've alredy taken this path.")
else:
user_save["path_2"] = "Completed"
print("Congrats on finishing this path!")
chosen_path = input("Would you like to choose path 2A or 2B?: ").lower()
if chosen_path == "2a":
path_2a()
elif chosen_path == "2b":
path_2b()
else:
print("Sorry that isn't a valid path. Please try again.")
while ("path_1" and "path_2") not in user_save:
start_button()
if "path_1" and "path_2" in user_save:
print("Congrats on finishing the game!")
我希望循环继续运行,直到用户选择了路径 1 和 2。一旦两个键都在字典中,我想打印一条祝贺消息并打破循环。就像我之前说的大多数代码运行良好。如果用户先选择 path_2a 然后选择 2b,则即使他们选择不存在的路径,循环也会完全按照我的意愿进行。只有当用户首先选择 path_2b 时。感谢您的帮助!
【问题讨论】:
-
("path_1" and "path_2") not in user_save和"path_1" and "path_2" in user_save不要做你认为他们做的事。 -
你说循环中断了,是什么错误?
-
("path_1" and "path_2")总是返回True所以你的 while 循环等同于True not in user_save这绝对不是你要找的。您需要扩展每个子句"path_1" not in user_save and "path_2" not in user_save或查看all()内置函数。 -
我应该纠正自己。循环不会“中断”,但似乎当用户首先选择 path_2b 时,它会继续前进并打印“恭喜完成游戏”并停止运行,即使只有 path_2b 已添加到字典中,但它应该只在两者都停止运行时才停止运行存在路径。
-
我试图扩展 not in 子句,但我最终遇到了同样的问题。我应该在哪里使用 all()?
标签: python python-3.x dictionary if-statement while-loop