【问题标题】:Need to close a while loop with a user input需要用用户输入关闭一个while循环
【发布时间】:2022-01-17 22:35:51
【问题描述】:

我正在尝试制作一个问琐事问题的小游戏。我几乎准备好了,但我不知道如何关闭我的 while 循环。

while True:
        Choose = input("What topic would you like?")
        if Choose == "History" or Choose == "history":
            import History
            break
        elif Choose == "Geo" or Choose == "geo" or Choose == "geography" or Choose == "Geography":
            import Geo
            break
        elif Choose == "I'm done!":
            print("Thanks for playing!")
            break
        else: 
            print("Sorry, please enter a valid topic")
            continue

【问题讨论】:

  • break 结束循环。当他们输入有效输入而不是无效输入时,您应该这样做。
  • “关闭”循环是什么意思?在 Python 中,你不必声明你关闭一个块,它都是由缩进指定的。
  • 不需要try/except。您没有进行任何可能引发异常的类型转换。
  • 关闭是什么意思?您在 else 语句中有一个 break,当有人输入无效主题时,它会退出 while 循环。
  • @Barmar 这帮了大忙!谢谢!

标签: python while-loop


【解决方案1】:
while True:
    Choose = input("What topic would you like?")
    if Choose == "History" or Choose == "history":
        import History
    elif Choose == "Geo" or Choose == "geo" or Choose == "geography" or Choose == "Geography":
        import Geo
    elif Choose == 'quit':
        print("Ok, bye bye!")
        break
    else: 
        print("Sorry, please enter a valid topic")

一些您可能会感兴趣的细节:

Choose.lower() == "history"

可以用来代替 if X 或 x。这也适用于 Geo/geo 等。

用小写命名变量通常是标准。 choose

【讨论】:

  • 非常感谢!这将非常有帮助!
猜你喜欢
  • 2013-11-16
  • 2020-02-15
  • 2017-08-09
  • 1970-01-01
  • 2016-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多