菜鸟:数字猜测游戏

时间:2017-10-15 21:56:21

标签: python

我正在尝试编写一个小练习,其中用户猜测一个数字,被引导得更高或更低,当他们正确猜测时退出,并在他们的输入“退出”时退出。当我进入“退出”时,如果我的猜测太高,控制台会返回相同的响应。我不知道如何解决这个问题。另外,我对我的基本代码有任何改进建议。

from random import randrange

number = randrange(0,11)

guess = False
counter = 0

while guess == False:
    guess = input("Guess the number (1-10): ")
    if guess < number:
        print "Guess a bit higher."
        print
        guess = False
    elif guess > number:
        print "Guess a bit lower."
        print
        guess = False
    elif guess == number: 
        print
        print "Right on the money!"
        print "Amount of attempts:", counter
        guess = True
    else:
        guess == "Exit"
        print "Thanks for playing, I guess.", counter
        guess = True
    counter += 1

1 个答案:

答案 0 :(得分:1)

这是在Python3中完成的。看看guess是否是一个数字,如果是,则将猜测改为int。如果不是,它将作为一个字符串继续猜测并退出。

from random import randrange

number = randrange(0,11)

guess = False
counter = 0

while guess == False:
    guess = input("Guess the number (1-10): ")
    if guess.isdigit():
        guess=int(guess)
        if guess < number:
            print ("Guess a bit higher.")
            print
            guess = False
        elif guess > number:
            print ("Guess a bit lower.")
            print
            guess = False
        elif guess == number: 
            print
            print ("Right on the money!")
            print ("Amount of attempts:", counter)
            guess = True

    else:
        guess == "Exit"
        print ("Thanks for playing, I guess.", counter)
        guess = True
        guess=str(guess)

    counter += 1