数字猜谜游戏

时间:2015-04-28 01:57:27

标签: python python-2.7

import random 
def guess_number():
    numb = random.randrange (10) +1
    guessestaken = 0
    guess = input("whats your number")
    while (guess != numb):
            if (guess > numb):
                print "too low"
            elif(guess < numb):
                print "too high"

            else:
                input("whats your next numb")
                tries += 1

我正在制作一个范围为1到10的数字猜谜游戏,我需要帮助才能让循环停止。当我猜它继续的数字时

2 个答案:

答案 0 :(得分:1)

您永远不会在循环中重新分配guess,因此guess != numb的真值永远不会改变。将guess =放在循环中的input()调用之前,或将其重组为while True: ... break布局。此外,如果用户完全正确,您只能给用户另一个猜测数字的机会。慢慢阅读您的代码,并尝试跟随解释器正在做的事情。

答案 1 :(得分:1)

以下是您尝试做的工作示例:

import random 

guessesTaken = 0
number = random.randint(1, 20)
print('I am thinking of a number between 1 and 20.')

while guessesTaken < 6:
     print('Take a guess.\n')
     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, You guessed my number in ' + guessesTaken + ' guesses!')

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