python比较条件中的整数

时间:2015-03-22 15:05:52

标签: python integer comparison

作为一名Java程序员,我将教一些孩子Python。我负责创建一个数字猜测游戏,经过一些课程后介绍。

from random import randrange

print("hi I've a number below 100 can you guess??");
theNumber = randrange(100)
theAnswer = raw_input("your first guess >")
while theNumber != theAnswer :
    print (str(theAnswer) + " .. " + str(theNumber) + str(theAnswer > theNumber))
    if theAnswer > theNumber:
        print ("you answer is too large")
    else :
        print ("you answer is too small")

    theAnswer = raw_input("your next guess >")

print ("You guessed!")

看起来我的数字比较出错了。因为在我第一次猜测后,我看到了:

hi I've a number below 100 can you guess??
your first guess >50
50 .. 64True
you answer is too large

所以在上面的例子中,50大于64.我可能会忽略一些可怕的愚蠢,但此刻我没有抓住它。

1 个答案:

答案 0 :(得分:2)

一个有趣的节目!问题是raw_input将数字作为文字捕获,使用int会将其转换为数字:

from random import randrange

print("hi I've a number below 100 can you guess??");
theNumber = randrange(100)
theAnswer = int(raw_input("your first guess >"))
while theNumber != theAnswer :
    print (str(theAnswer) + " .. " + str(theNumber) + str(theAnswer > theNumber))
    if theAnswer > theNumber:
        print ("you answer is too large")
    else :
        print ("you answer is too small")

    theAnswer = int(raw_input("your next guess >"))

print ("You guessed!")