Skip to content Skip to sidebar Skip to footer

Check If Numbers Are In A Certain Range In Python (with A Loop)?

Here's my code: total = int(input('How many students are there ')) print('Please enter their scores, between 1 - 100') myList = [] for i in range (total): n = int(input('Enter

Solution 1:

whileTrue:
   n = int(input("enter a number between 0 and 100: "))
   if0 <= n <= 100:
      breakprint('try again')

Just like the code in your question, this will work both in Python 2.x and 3.x.

Solution 2:

First, you have to know how to check whether a value is in a range. That's easy:

if n in range(0, 101):

Almost a direct translation from English. (This is only a good solution for Python 3.0 or later, but you're clearly using Python 3.)

Next, if you want to make them keep trying until they enter something valid, just do it in a loop:

for i inrange(total):
    whileTrue:
        n = int(input("Enter a test score >> "))
        if n inrange(0, 101):
            break
    myList.append(n)

Again, almost a direct translation from English.

But it might be much clearer if you break this out into a separate function:

defgetTestScore():
    whileTrue:
        n = int(input("Enter a test score >> "))
        if n inrange(0, 101):
            return n

for i inrange(total):
    n = getTestScore()
    myList.append(n)

As f p points out, the program will still "just end with a error" if they type something that isn't an integer, such as "A+". Handling that is a bit trickier. The int function will raise a ValueError if you give it a string that isn't a valid representation of an integer. So:

defgetTestScore():
    whileTrue:
        try:
            n = int(input("Enter a test score >> "))
        except ValueError:
            passelse:
            if n inrange(0, 101):
                return n

Solution 3:

You can use a helper function like:

definput_number(min, max):
    whileTrue:
        n = input("Please enter a number between {} and {}:".format(min, max))
        n = int(n)
        if (min <= n <= max):
            return n
        else:
            print("Bzzt! Wrong.")

Post a Comment for "Check If Numbers Are In A Certain Range In Python (with A Loop)?"