简体   繁体   English

如何在python中正确退出程序

[英]How to properly quit a program in python

Im a middle school student, and im starting to learn coding in python.我是一名中学生,我开始学习 Python 编码。 I have been watching video tutorials, but i cant seem to figure out how to make the game quit if you type q.我一直在看视频教程,但我似乎无法弄清楚如果您键入 q 时如何退出游戏。 here what i have..在这里,我有什么..

print('How old do you thing Fred the Chicken is?')
number = 17

Quit = q
run = 17
while run:

guess = int(input('Enter What You Think His Age Is....'))

print('How old do you thing Fred the Chicken is?')
number = 17

Quit = 'q'
run = 17
while run:

guess = int(input('Enter What You Think His Age Is....'))

if guess == number:
    print('Yes :D That is his age...')
    run = False
elif guess < number:
    print('No, Guess a little higher...')
elif guess > number:
    print('No, Guess a little lower....')

print('Game Over')
print('Press Q to Quit')

if run == False:
choice = input('Press Q to Quit')
if choice == 'q'
import sys
exit(0)

Getting Q as inputQ作为输入

Quit = int(input('Press Q to Quit')

You're asking for Q as the input, but only accepting an int .您要求Q作为输入,但只接受一个int So take off the int part:所以int部分:

Quit = input('Press Q to Quit')

Now Quit will be whatever the user typed in, so let's check for "Q" instead of True :现在Quit将是用户输入的任何内容,所以让我们检查“Q”而不是True

if Quit == "Q":

Instead of sys.exit(0) , you can probably just end your while look with break or just return if you're in a function.而不是sys.exit(0) ,你可能只是用break结束你的 while 外观,或者如果你在一个函数中就return

Also, I don't recommend the name "Quit" for a variable that just stores user input, since it will end up confusing.另外,我不建议为仅存储用户输入的变量使用名称“退出”,因为它最终会令人困惑。

And remember that indentation is important in Python, so it needs to be:请记住,缩进在 Python 中很重要,因此它必须是:

if run == False:
    choice = input('Press Q to Quit')
    if choice == "Q":
        # break or return or..
        import sys
        sys.exit(0)

That may just be a copy/paste error though.不过,这可能只是复制/粘贴错误。

Indentation and Syntax缩进和语法

I fixed the indentation and removed some extraneous code (since you duplicate the outer loop and some of the print statements) and got this:我修复了缩进并删除了一些无关的代码(因为您复制了外部循环和一些打印语句)并得到了这个:

print('How old do you thing Fred the Chicken is?')
number = 17

run = True
while run:

    guess = int(input('Enter What You Think His Age Is....t'))

    if guess == number:
        print('Yes :D That is his age...')
        run = False
    elif guess < number:
        print('No, Guess a little higher...')
    elif guess > number:
        print('No, Guess a little lower....')

    if run == False:
        print('Game Over')
        choice = input('Press Q to Quit')
        if choice == 'q'
            break

This gave me a syntax error:这给了我一个语法错误:

blong@ubuntu:~$ python3 chicken.py blong@ubuntu:~$ python3 chicken.py
File "chicken.py", line 23文件“chicken.py”,第 23 行
if choice == 'q'如果选择 == 'q'
^ ^
SyntaxError: invalid syntax语法错误:无效语法

So Python is saying there's something wrong after the if statement.所以 Python 说if语句之后有问题。 If you look at the other if statements, you'll notice that this one is missing the : at the end, so change it to:如果您查看其他if语句,您会注意到这个语句的末尾缺少: ,因此将其更改为:

if choice == 'q':

So with that change the program runs, and seems to do what you want.因此,随着该更改,程序会运行,并且似乎可以执行您想要的操作。

Some suggestions一些建议

  • Your instructions say "Press Q to Quit", but you actually only accept "q" to quit.您的说明说“按 Q 退出”,但实际上您只接受“q”退出。 You may want to accept both.您可能想同时接受两者。 Python has an operator called or , which takes two truth values ( True or False ) and returns True if either of them is True (it actually does more than this with values besides True and False , see the documentation if you're interested). Python 有一个名为or运算符,它接受两个真值( TrueFalse ),如果它们中的任何一个为True则返回True (它实际上对TrueFalse之外的值做的比这更多,如果您有兴趣,请参阅文档)。

    Examples:例子:

     >> True or True True >>> True or False True >>> False or True True >>> False or False False

    So we can ask for Q or q with if choice == "Q" or choice == "q": .所以我们可以用if choice == "Q" or choice == "q":来请求 Q 或 q。

    Another option is to convert the string to lower case and only check for q , using if choice.lower() == "q": .另一种选择是将字符串转换为小写并只检查q ,使用if choice.lower() == "q": If choice was Q, it would first convert it to q (with the .lower() ), then do the comparison.如果choice是 Q,它将首先将其转换为 q(使用.lower() ),然后进行比较。

  • Your number is always 17. Python has a function called random.randint() that will give you a random number, which might make the game more fun.您的数字始终是17。Python有一个名为random.randint()的函数,它会给您一个随机数,这可能会使游戏更有趣。 For example, this would make the chicken's age between 5 and 20 (inclusive):例如,这将使鸡的年龄在 5 到 20(含)之间:

     number = random.randint(5, 20)

There are many ways to exit certain things.有很多方法可以退出某些事情。 For loops, it is using break , and for functions you can use return .对于循环,它使用break ,而对于函数,您可以使用return However, for programs, if you wish to exit your program before interpretation finishes (end of the script) there are two different types of exit() functions.但是,对于程序,如果您希望在解释完成(脚本结束)之前退出程序,则有两种不同类型的exit()函数。 There is sys.exit() which is part of the sys module, and there is exit() and quit() which is a built-in. sys.exit()sys模块的一部分, exit()quit()是内置的。 However, sys.exit() is intended for programs not in IDLE (python interactive), while the built-in exit() and quit() functions are intended for use in IDLE.但是, sys.exit()用于不在 IDLE 中的程序(python 交互),而内置的exit()quit()函数用于在 IDLE 中使用。

You can use the break statement to break out of a while loop:您可以使用break语句跳出while循环:

while True:
    guess = int(input("...")

    # ...rest of your game's logic...

    # Allow breaking out of the loop
    choice = input("Enter Q to quit, or press return to continue")
    if choice.lower() == "q":
        break

That means the interpreter exits the while loop, continues looking for more commands to run, but reaches the end of the file!这意味着解释器退出while循环,继续寻找更多要运行的命令,但到达文件末尾! Python will then exit automatically - there's no need to call sys.exit Python 将自动退出 - 无需调用sys.exit

(as an aside, you should rarely use sys.exit , it's really just used to set non-zero exit-status , not for controlling how your program works, like escaping from a while loop) sys.exit ,您应该很少使用sys.exit ,它实际上只是用于设置非零exit-status而不是用于控制程序的工作方式,例如从while循环中转义)

Finally, the main problem with the code you posted is indentation - you need to put the appropriate number of spaces at the start of each line - where you have something like:最后,您发布的代码的主要问题是缩进 - 您需要在每行的开头放置适当数量的空格 - 您有以下内容:

if run == False:
choice = input('Press Q to Quit')

It must be like this:必须是这样的:

if run == False:
    choice = input('Press Q to Quit')

Same with anything like while , for , if and so on.whileforif等类似。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM