Python while循环/范围

时间:2011-11-07 21:06:25

标签: python

我需要向用户询问一个数字,然后如果它在低/高数字的范围内,则它返回数字,如果它不在范围内,它会循环,直到输入的数字在范围内。我真的不知道如何做到这一点,但我认为我有一部分是正确的。我主要担心的是“虽然问题!=低< =问题< =高:”我觉得这条线路有问题。

def ask_number(question, low, high):
    question = int(raw_input("Enter a number within the range: "))
    question = ""
    while question != low <= question <= high:
        question = int(raw_input("Enter a number within the range: "))

4 个答案:

答案 0 :(得分:3)

在这种情况下,最简单的解决方案是使用True作为while循环中的条件,并在循环内部使用if进行分解,如果数字正常:< / p>

def ask_number(low, high):
    while True:
        try:
            number = int(raw_input("Enter a number within the range: "))
        except ValueError:
            continue
        if low <= number <= high:
            return number

我还添加了try / except语句,以防止程序在用户输入无法转换为数字的字符串时崩溃。

答案 1 :(得分:3)

如果您这样想的话,你的while循环语法会更清晰:“我想继续向用户询问答案,而他们的答案低于或高于高。”直接翻译成Python,这将是

while question < low or question > high:

您也不应将""分配给question,因为这会覆盖用户的第一个答案。如果他们第一次得到该范围内的数字,他们仍将再次被询问。基本上,你应该删除这一行:

question = ""

您的最终代码应如下所示:

def ask_number(low, high):
    assert low < high
    question = int(raw_input("Enter a number within the range: "))
    while question < low or question > high:
        question = int(raw_input("Enter a number within the range: "))
    return question

print(ask_number(5,20))

答案 2 :(得分:0)

def ask_number(low, high):  
    while True:
        number = int(raw_input('Enter a number within the range: '))
        if number in xrange(low, high + 1):
            return number

答案 3 :(得分:0)

def ask_number(low, high):

    """question cannot be less than the minimum value so we set it below the
    minimum value so that the loop will execute at least once."""

    question = low - 1

    """You want question to be within the range [high, low] (note the
    inclusivity), which would mathematically look like 'low <= question <= high'.
    Break that up into what appears to be one comparison at a time:
    'low <= question and question <= high'. We want the while loop to loop when
    this is false. While loops loop if the given condition is true. So we need to
    negate that expression. Using the DeMorgan's Theorem, we now have
    'low < question or question > high'."""

    while question < low or question > high:

        """And this will obviously update the value for question. I spruced up
        the only argument to raw_input() to make things a bit 'smoother'."""

        question = int(raw_input("Enter a number within the range [%d, %d]: " % _
                   (low, high)))

    # Return question.
    return question