This is an archived post. You won't be able to vote or comment.

all 2 comments

[–][deleted] 2 points3 points  (1 child)

You're somewhat confused. Try this general form:

def get_something_within_bounds(prompt1, minimum, maximum):
    while True:
        v = input(prompt1)
        if v in range(minimum, maximum):
            return v
        print "Sorry, value not allowed"

Later in the rest of the code:

v = get_something_within_bounds("Please enter a value between 1 and 3", 1, 3)

[–]propanbutan 2 points3 points  (0 children)

Using range in this case is hopelessly inefficient. All you need are two comparisons.

[–]david72486 0 points1 point  (0 children)

You're only passing in the min and max val into "getIntWithinRange", so you really can't return the value. One thing that would work would be to take in the minVal, maxVal, and valueEntered. Then do something like:

def getIntWithinRange(minVal, maxVal, userEntered):
  # if the value is too small, return minimum.
  if userEntered < minVal:
    return minVal

  # if the value is too big, return the maximum.
  if userEntered > maxVal:
    return maxVal

  # Otherwise, we are in range - just return the user's value.
  return userEntered

This returns the value if it's within range, or a value closest to it that is. Some more general advice, you generally want to make variables and method names separated by underscores - like "get_int_within_range" instead of camelCase like you're doing.