猜猜随机数游戏python

时间:2016-10-26 15:35:34

标签: python random

我的程序应该要求用户猜出0到100之间的数字,但我似乎无法正确输出。目前,如果用户号码大于随机数,则打印出无限量的"您的号码太高。"此外,如果第一个UserGuess为低,则以下所有数字都将具有相同的提示:("您的数字太低")尽管它们实际上大于随机数。我不知道我做错了什么。任何帮助将不胜感激。谢谢!

from random import randint

def main():


    guessesTaken = 0

    randomNumber = randint(0,100)
    #print(randomNumber)
    giveUp = -1
    UserGuess = int(input("Take a guess" + "(The random number is: " + str(randomNumber) + "): "))

    while UserGuess != randomNumber:

        guessesTaken += 1

        if UserGuess < randomNumber:
            UserGuess = int(input("Your guess is too high.Try again: "))

        elif UserGuess > randomNumber:
            UserGuess = int(input("Your guess is too high.Try again: "))

        elif UserGuess == randomNumber or UserGuess == giveUp:
            break

    if UserGuess  == randomNumber:
        guessesTaken = str(guessesTaken)
        print("Yes, that is right!")
        print("It took you " + guessesTaken +  " guesses")
    if UserGuess == giveUp:
        guessesTaken = str(guessesTaken)
        randomNumber = str(randomNumber)
        print("Better luck next time.")
        print("You tried"+ guessesTaken +  " guesses")


    return
    print (main())

if __name__ == "__main__":
     main()    

1 个答案:

答案 0 :(得分:3)

进入循环后,您需要获得更多用户输入。考虑

UserGuess = None

while UserGuess != randomNumber:
    UserGuess = int(input("Take a guess" + "(The random number is: " + str(randomNumber) + "): "))
    guessesTaken += 1
    ....

就目前而言,你只是第一次猜测。然后你反复重新评估它。由于用户无法改变猜测,因此无限循环。

此外,您还需要更改if / elifs的顺序。

目前,结构是

if guess (is too low)
if the guess (is not too low), and (is too high)
if the guess (is not too low), and (is not too high), and (is correct) or (is 'give up')

让它运作的快捷方式是

if   UserGuess == randomNumber or UserGuess == giveUp:
    ...
elif UserGuess > randomNumber:
    ...
elif UserGuess < randomNumber:
    ....