在Python 3中找到用户输入的猜测数字

时间:2018-09-25 11:13:50

标签: python python-3.x

我在python 3中编写了一个代码,其中包括用于查找数字的二进制serach算法。用户将输入0,1或2作为更高或更低的点。因此,我使用以下代码:

def guess():
    i = 0
    # i is the lowest number in range of possible guess
    j = 100
    # j is the highest number in range of possible guesses
    m = 50
    # m is the middle number in range of possible guesses
    counter = 1
    # counter is the number of guesses take.
    print ("Please guess a number")
     condition = input("Is your guess " + str(m) + "? (0 means it's 
     too low, 1 means it's your guess and 2 means it's too high) ")
    while condition != 1:
         counter += 1
         if condition == 0:
            i = m + 1
         elif condition == 2:
              j = m - 1
         m = (i + j)//2
         condition = input("Is your guess " + str(m) + "? (0 means 
         it's too low, 1 means it's your guess and 2 means it's too 
          high) ")
     print ("It took" , counter , "times to guess your number")
guess()

好的,我运行后,输出如下:

Please guess a number
Is your guess 50? (0 means it's too low, 1 means it's your guess and 2 means 
it's too high) 0

当我输入0

Is your guess 50.0? (0 means it's too low, 1 means it's your guess and 2 
means it's too high) 

它的结果始终为50.0,但应低于50。 有什么办法可以减少程序中的数字。谢谢!

2 个答案:

答案 0 :(得分:4)

您需要将输入转换为整数,它将输入作为字符串读取。

condition = int(input("Is your guess " + str(m) + "? (0 means it's 
    too low, 1 means it's your guess and 2 means it's too high) ").strip())

通过strip,它将在将字符串转换为整数之前负责删除空格和换行符。

答案 1 :(得分:2)

在Python 3中,input()将始终返回字符串。因此,诸如condition == 0condition == 2之类的比较将始终返回false。

相反,请尝试检查condition == '0'condition == '2'。更一般而言,您可能应该考虑用户可能输入了0、1或2以外的内容并显示错误消息。那本可以帮助您捕获此错误!