你如何重启python猜数字游戏?

时间:2013-06-18 01:58:31

标签: python-3.x numbers

我是python的新手,所以我无法弄清楚如何让这个代码重新开始重复。这是我的代码:

import random

guessesTaken = 0

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)

    guessesTaken = guessesTaken + 1

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

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

    if guess == number:
        break

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

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

谢谢你们,请尽快回复,

3 个答案:

答案 0 :(得分:1)

将当前代码放在函数中,然后根据需要多次调用它。例如:

import random

def main():
    n_games = 5
    for n in range(n_games):
        play_guessing_game()

def play_guessing_game():
    # Your code here.
    print("Blah blah")

main()

更好的方法是接受n_games作为命令行参数(sys.argv[1])。更好的是停止编写交互式猜谜游戏(咆哮:为什么人们会教这些东西?)而是学习如何编写一个二进制搜索功能。

答案 1 :(得分:1)

这一定是您一直在寻找的代码

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
    while inplay == True:
        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)
        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 :(得分:1)

将您的代码放入一个函数中,然后创建另一个函数,询问用户是否想再次播放。

def main():
    game = "your game"
    print(game)
    play_again()

def play_again():
    while True:
        play_again = input("Would you like to play again?(yes or no) > ")
        if play_again == "yes"
            main()
        if play_again == "no"
            exit()
        else:
            print("I'm sorry I could not recognize what you entered")
main()