循环直到条目匹配预定值

时间:2015-03-15 14:36:32

标签: python python-2.x

我希望有一个用户尝试猜谜游戏。程序应该循环,直到用户猜对了 我该如何比较这些值?现在它每次都会通过其他部分,即使用户猜对了 这是代码;

import sys
from random import randint

secret_number = randint(0, 100)
num_guesses = 0
guess = 0


while guess != secret_number:
    guess = raw_input("Enter a number: ")

    if (guess < secret_number):
        print "Your guess is too low. Please try again."

    else:
        print "Your guess is too high. Please try again."
    num_guesses = num_guesses + 1

print "Thank you, you guessed right"

print guess

2 个答案:

答案 0 :(得分:3)

您需要使用raw_inputint返回的字符串转换为整数,因此比较运算符的工作方式符合您的预期:

guess = int(raw_input("Enter a number: "))

答案 1 :(得分:2)

raw_input将返回字符串,您将字符串与int进行比较并且无效

你也永远猜不到这个数字: 您的代码有2个选项:太低或太高

你也绝不会将尝试与最大尝试进行比较(尝试自己修复)

更正后的版本:

import sys
from random import randint

secret_number = randint(0, 100)
num_guesses = 0
guess = 0


while guess != secret_number:
    guess = raw_input("Enter a number: ")

    if (int(guess) < secret_number):
        print "Your guess is too low. Please try again."

    elif (int(guess) > secret_number) :
        print "Your guess is too high. Please try again."
    else:
        print "Thank you, you guessed right"
        break

num_guesses = num_guesses + 1



print guess