python 比较条件中的整数

python comparing integers in conditions

作为一名 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。我可能忽略了一些非常愚蠢的东西,但目前我没有明白。

一个有趣的节目!问题是 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!")