猜猜游戏只会认为猜测太高了

时间:2015-01-26 15:32:51

标签: python

有谁知道为什么这个函数只打印出猜测太高?关于如何解决的想法?

from __future__ import print_function
import random
def goguess():
    HighNumber= random.randint(1,100)
    LowNumber= random.randint(1,HighNumber-1)
    answer = random.randint(LowNumber+1,HighNumber)
    guesses = 0
    print ('I have a number between', LowNumber, 'and', HighNumber, 'inclusive.')
    guess = raw_input('guess:')
    while guess != answer:
        if guess > answer:
            print(guess, 'is too high.')
            guesses+=1
            print('Guess:', guesses)
            guess = raw_input('guess:')
        if guess < answer:
            print(guess, 'is too low')
            guesses+=1
            print('Guess:',guesses)
            guess = raw_input('guess:')
    if guess == answer:
        print ('Right! My number is', answer,'! You guessed in ',guesses, 'guesses!')  

2 个答案:

答案 0 :(得分:4)

您需要将其输入转换为int

guess = int(raw_input('guess:'))

否则,您要将strint进行比较,str将始终更大。

>>> '3' > 7
True
>>> int('3') > 7
False

在Python 3.x中你会以更明显的方式看到这个问题,因为你不能再像这样比较这些类型了

>>> '3' > 7
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    '3' > 7
TypeError: unorderable types: str() > int()

答案 1 :(得分:0)

猜猜必须是一个整数才能与整数进行比较。 raw_input返回整数的字符串。可以使用int()将字符串转换为整数。之后

guess = raw_input('Guess')

您可以存储

intguess = int(guess)