我目前正在尝试构建一个非常简单的程序,在该程序中,要求用户选择路径,并根据所选择的路径来更新词典。看来,当用户首先选择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时。感谢您的帮助!
答案 0 :(得分:0)
代替将函数放入函数中,请尝试以下操作。我已简化为使用“ 2a”和“ 2b”作为实际的键名。另外,由于2a和2b都确定您要退出的时间,因此可以跳过while
循环,而只使用一个在选择2a和2b后退出的函数,否则将继续运行。
def play_game(user_save):
chosen_path = input("Would you like to choose path 2A or 2B?: ").lower()
if chosen_path not in ['2a', '2b']:
print("Sorry that isn't a valid path. Please try again.")
elif chosen_path in user_save:
print("You've already taken this path.")
else:
user_save[chosen_path] = "Completed"
print("Congrats on finishing this path!")
# If both 2a and 2b have been taken, just "return" to exit.
if '2a' in user_save and '2b' in user_save:
print("Congrats on finishing the game!")
return
# If they're still here, loop it again. Take the updated
# dictionary <user_save> as input for the next round.
play_game(user_save)
# Run the program
user_save = {}
play_game(user_save)
答案 1 :(得分:0)
根据您的代码,您需要更改代码:
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_2" not in user_save or "path_1" not in user_save:
start_button()
if "path_2" in user_save and "path_1" in user_save:
print("Congrats on finishing the game!")