【问题标题】:Running a while loop if keys aren't in a dictionary如果键不在字典中,则运行 while 循环
【发布时间】: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


【解决方案1】:

根据您的代码,您需要更改代码:

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

【讨论】:

    【解决方案2】:

    不要将函数放在函数中,而是尝试以下操作。我已将其简化为使用“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)
    

    【讨论】:

    • 感谢您的详细解释!那里的逻辑似乎更简单,更有效。我不知道你可以使用我认为你需要一个循环来做到这一点的方式。目前正在自学,所以一切都有帮助。不过,我确实对您的代码有一个疑问。使用 user_save 中的 if '2a' 和 user_save: 语句中的 '2b',如果除了字典中的列表之外还有其他数据类型,这可能会导致冲突吗? '2a' 和 '2b' 到底是什么类型的数据?
    • 不客气! '2a' 和 '2b' 只是字符串本身。如果您的键不是字符串(例如,您的字典类似于'{1:“完成”,2:“完成”}'),那么您必须检查整数。尽管另一个考虑是,如果您只检查一个键是否在字典中,您可以只使用列表而不是字典(例如,如果采用路径 2a,则 append"2a" 到列表)。是的,在函数中使用命令来调用自身(也称为“递归”或“递归函数”)是另一种可以“循环”某些内容的有用方式。
    猜你喜欢
    • 2019-05-03
    • 2017-07-18
    • 2015-12-28
    • 2019-03-17
    • 2020-03-01
    • 2021-07-22
    • 2020-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多