【问题标题】:How to allow a user to quit a program如何允许用户退出程序
【发布时间】:2016-11-15 00:22:48
【问题描述】:

我正在制作一款文字冒险游戏,并试图让用户使用 q 退出游戏。我不知道该输入什么,这是我的代码。

print ("Welcome to Camel!")
print ("You have stolen a camel to make your way across the great Mobi deset.")
print ("The natives want their camel back and are chasing you down! Survive your desert trek and out run the natives.")

print ("Welcome to Camel!")
print ("You have stolen a camel to make your way across the great Mobi deset.")
print ("The natives want their camel back and are chasing you down! Survive your desert trek and out run the natives.")

done = False
while done == False:
    print("Print the letter only.")
    print("A. Drink from your canteen.")
    print("B. Ahead moderate speed.")
    print("C. Ahead full speed.")
    print("D. Stop for the night.")
    print("E. Status check.")
    print("Q. Quit.")

    first_question = input("What do you want to do? ")

    if first_question.lower() == "q":
        done = True

    if done == True:
        quit

代码中的所有行都正确缩进(网站在复制粘贴时会变得很奇怪)。任何帮助表示赞赏。

【问题讨论】:

  • 我将您的代码编辑成代码块。以后你可以高亮这段代码,然后点击大括号{}的按钮为你缩进
  • quit 是什么?也许你的意思是breakquit() - 和()。但是删除if done==True:quit,它应该可以正常工作。
  • 您可以使用if done: break if done: sys.exit()

标签: python exit


【解决方案1】:

你的程序几乎没有问题,事实上它在 python3 中运行得很好。问题在于,在 python2 中,input 实际上会评估您的输入。为了支持python2,请使用raw_input

【讨论】:

    【解决方案2】:
    print ("Welcome to Camel!")
    print ("You have stolen a camel to make your way across the great Mobi deset.")
    
    print ("The natives want their camel back and are chasing you down! Survive your desert trek and out run the natives.")
    
    done = False
    
    while done == False:
    
        print("Print the letter only.")
    
        print("A. Drink from your canteen.")
    
        print("B. Ahead moderate speed.")
    
        print("C. Ahead full speed.")
    
        print("D. Stop for the night.")
    
        print("E. Status check.")
    
        print("Q. Quit.")
    
        first_question = input("What do you want to do? ")
    
        if first_question.lower() == "q":
    
            done = True
    
            if done == True:
    
                break
    

    现在,当你输入 'Q' 或 'q' 程序将退出。 这是关于制表的。这是你问的吗?

    【讨论】:

    • quit 是内置的退出方法
    • 据我所知,我们使用break 来打破循环,女巫我真的看不到这里。所以quit 会做并且它有效。
    • @leaf 我明白了。因此,当我们使用 while/if break 时,将是正确的停止方式。但是,quit 也可以在这里工作吗?
    • @IgorStepanov 是的。确实如此。但正如我在之前的评论中所说,quit 不应该在实际程序中使用,per the Python docs
    • @leaf 好的,下次我会记住这一点。我也在学习,所以不要严格评判我
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-26
    • 1970-01-01
    • 1970-01-01
    • 2018-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多