简体   繁体   中英

How to properly quit a program in python

Im a middle school student, and im starting to learn coding in python. I have been watching video tutorials, but i cant seem to figure out how to make the game quit if you type 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 input

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

You're asking for Q as the input, but only accepting an int . So take off the int part:

Quit = input('Press Q to Quit')

Now Quit will be whatever the user typed in, so let's check for "Q" instead of 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.

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:

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
File "chicken.py", line 23
if choice == 'q'
^
SyntaxError: invalid syntax

So Python is saying there's something wrong after the if statement. 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 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. 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).

    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": .

    Another option is to convert the string to lower case and only check for q , using if choice.lower() == "q": . If choice was Q, it would first convert it to q (with the .lower() ), then do the comparison.

  • 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. For example, this would make the chicken's age between 5 and 20 (inclusive):

     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 . 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. There is sys.exit() which is part of the sys module, and there is exit() and quit() which is a built-in. 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.

You can use the break statement to break out of a while loop:

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! Python will then exit automatically - there's no need to call 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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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