"猜猜我的号码"游戏与一个循环

时间:2014-11-12 16:58:24

标签: python python-2.7 while-loop

我想制作一个程序,要求用户考虑0100之间的数字并尝试猜测。

所以这是我目前的代码:

k = raw_input('Think about a number between 0 and 100. (Enter/Return?): ')
x = 'a'
i = 100

if k == 'Enter':
    i = i/2
    while x != 'correct':
        print 'the number is:', i
        x = raw_input('is this the number? (bigger,smaller,correct): ')
        if x == 'smaller':
            i = i/2
        elif x == 'bigger':
            i = i + i/2
        elif x == 'correct':
            print 'Yupiiii!!'
        else:
            print 'Invalid answer'

我对该计划的主要问题是我无法限制其猜测"范围。

例如:如果它显示50并且我说它更大会猜测75,那么如果我说更小则会猜测3737不是5075之间的数字;如何在这段时间内猜出一个数字?

如果我继续说'bigger',它也会超过100。

有什么建议吗?

2 个答案:

答案 0 :(得分:3)

这是一个简单的实现(使用-1代表更低版本,0代表更高版本,1代表更高版本),专注于如何跟踪有效的输入范围:

def get_int_input(prompt, min_=None, max_=None):
    """Take valid input from the user.

    Notes:
      Valid input is an integer min_ <= input <= max_. By default,
      no limits are applied.

    """
    ...

def guess_my_number(min_=0, max_=100):
    """Guess the number the user is thinking of."""
    print "Think of a number between {} and {}.".format(min_, max_)
    prompt = "Is it {}? "
    while True:
        guess = min_ + ((max_ - min_) // 2) # guess the middle of the range
        result = get_int_input(prompt.format(guess), -1, 1)
        if result > 0:
            min_ = guess # must be bigger than guess
        elif result < 0:
            max_ = guess # must be smaller than guess
        else:
            break # done

在游戏中:

>>> guess_my_number()
Think of a number between 0 and 100.
Is it 50? -1
Is it 25? 1
Is it 37? 1
Is it 43? -1
Is it 40? 1
Is it 41? 1
Is it 42? 0

请注意,制作min_max_参数可让您轻松提出不同的问题:

>>> guess_my_number(1, 10)
Think of a number between 1 and 10.
Is it 5? 1
Is it 7? 0

答案 1 :(得分:0)

您需要跟踪数字可能在的范围的两端,而不仅仅是顶部。