你如何结束python猜数字游戏?

时间:2013-06-18 23:47:29

标签: python python-3.x

我在@J DawG的帮助下创建了一个循环猜测数字游戏,但是我无法弄清楚如果用户告诉它如何终止它。这是我的代码:

import random

inplay = 0
x = ""
def in_play():
    global inplay, guessesTaken
    guessesTaken = 0
    if inplay == True:
        play()
    else:
        inplay = True
        play()

def play():
    global guessesTaken
    print('Hello! What is your name?')
    myName = input()

    number = random.randint(1, 20)
    print('Well, ' + myName + ', I am thinking of a number between 1 and 20.')

    while guessesTaken < 5:
        print('Take a guess.') 
        guess = input()
        guess = int(guess) or str(guess)
        guessesTaken = guessesTaken + 1

        if guess < number:
            print('Your guess is too low.') 

        elif guess > number:
            print('Your guess is too high.')

        elif guess == number:
            break

    if guess == number:
        guessesTaken = str(guessesTaken)
        print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + '   guesses!')
        in_play()

    elif guess != number:
        number = str(number)
        print('Nope. The number I was thinking of was ' + number)
        in_play()


in_play()

所以,是的,如果你能在相对较快的时候回答这个问题,那就太棒了。

2 个答案:

答案 0 :(得分:1)

while guessesTaken < 5:更改为while guessesTaken < 5 and not finishedPlaying:。在开始时设置finishedPlaying = False并在提示用户询问他是否已完成时将其设置为True

顺便说一下,不要这样做:

guess = int(guess) or str(guess)

如果int(guess)无法工作,那么1)它将抛出一个异常,而不是返回类似虚假的值,2)你不能做任何事情 - 如果它不是一个数字那么它不是一个有效的猜测3)无论如何它都是一个字符串。

Python中or的语义是:评估我的第一个操作数。如果它在布尔上下文中是类似于true的值(如果对它False,则不会变为bool(operand)),返回它。否则,评估我的第二个操作数并将其返回。

答案 1 :(得分:-2)

您可以使用以下命令结束脚本:

import sys # put this at the top of the script
sys.exit() # when you want to end the script

例如,您可以让人们在输入中输入“exit”,检查它,并在发生时调用exit。