保持游戏进行直到用户键入退出,并打印出用户做了多少猜测?

时间:2016-12-15 08:17:49

标签: python python-3.x

我需要生成1到9的随机数,并要求用户猜测它。我告诉用户它是否过高,过低或正确。我无法弄清楚如何让游戏保持正常运行,一旦他们做对了,他们必须输入退出才能停止游戏。我还需要打印出最后为他们做了多少猜测。到目前为止,这是我的代码:

import random

while True:

    try:

        userGuess = int(input("Guess a number between 1 and 9 (including 1 and 9):"))

        randomNumber = random.randint(1,9)

        print (randomNumber)

    except:

        print ("Sorry, that is an invalid answer.")

        continue

    else:

        break

if int(userGuess) > randomNumber:

    print ("Wrong, too high.")

elif int(userGuess) < randomNumber:

    print ("Wrong, too low.")

elif int(userGuess) == randomNumber:

    print ("You got it right!")

3 个答案:

答案 0 :(得分:0)

import random
x = random.randint(1,9)
print x

while (True):
    answer=input("please give a number: ")
    if ( answer != x):
        print ("this is not the number: ")
    else:
        print ("You got it right!")
        break       

答案 1 :(得分:0)

以下是您的问题的解决方案:

Guessing Game One Solutions

import random

number = random.randint(1,9)
guess = 0
count = 0


while guess != number and guess != "exit":
    guess = input("What's your guess?")

    if guess == "exit":
        break

    guess = int(guess)
    count += 1

    if guess < number:
        print("Too low!")
    elif guess > number:
    print("Too high!")
    else:
        print("You got it!")
print("And it only took you",count,"tries!")

答案 2 :(得分:0)

from random import randint

while 1:
    print("\nRandom number between 1 and 9 created.")
    randomNumber = randint(1,9)

while 1:        
    userGuess = input("Guess a number between 1 and 9 (including 1 and 9). \nDigit 'stop' if you want to close the program: ")
    if userGuess == "stop":
        quit()
    else:
        try:
            userGuess = int(userGuess)
            if userGuess > randomNumber:
                print ("Wrong, too high.")

            elif userGuess < randomNumber:
                print ("Wrong, too low.")

            else:
                print ("You got it right!")
                break
        except:
            print("Invalid selection! Insert another value.")