0

I need to ask a number from the user and have then if it is in the range of the low/high number then it returns the number and if it isnt in the range, it loops until the number entered is in the range. I don't really know how exactly to do this but I think I have part of it right. My main concern is the line "while question != low <= question <= high:" I feel as if there is a problem with that line.

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: "))
1
  • I'm trying to create this game but I got my answer thanks Commented Nov 7, 2011 at 21:18

4 Answers 4

3

In this case, the easiest solution is to use True as the condition in the while loop, and an if inside the loop to break out if the number is fine:

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

I also added a try/except statement to prevent the program from crashing if the user enters a string that can't be converted to a number.

Sign up to request clarification or add additional context in comments.

2 Comments

If he wants to accept only integers (and not even accept (by truncating) floats then he could just do something like if number.isnumeric(): return int(number)
@TylerCrompton: You probably mean number.isdigit(), since isnumeric() does not exist. This would even rule out leading or trailing whitespace, so it's probably a bit too strict.
3

Your while loop syntax would be more clear if you thought of it this way: "I want to keep asking the user for the answer while their answer is less than low or greater than high." Translated directly to Python, this would be

while question < low or question > high:

You should also not assign "" to question as this overwrites the user's first answer. If they get the number in the range the first time, they will still be asked again. Basically, you should remove this line:

question = ""

Your final code should look something like this:

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 Comments

FYI, this code calls ask_number() with three arguments, but it only accepts two.
@AustinMarshall Thanks for catching that.
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

1 Comment

This is a bad idea. The Python 2.x xrange() object doesn't special-case the in operator, so this will loop over the range. Try 100000000 in xrange(200000000) to see what I mean. :) Also note that this works efficiently for Python 3.x range() objects.
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

2 Comments

His use of question = "" worked fine (on Python 2) as it will never be in the range low <= question <= high. "mathematically look like 'low <= question <= high'" Also Pythonically look like that; chained comparisons like that work fine.
But you can't chain the negation of that (unless you want to do not (<expression>). And yes, I understand that using "" is fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.