Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if numbers are in a certain range in python (with a loop)? [duplicate]

Tags:

python

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 a test score >> "))

    myList.append(n)

Basically I'm writing a program to calculate test scores but first the user has to enter the scores which are between 0 - 100.

If the user enters a test score out of that range, I want the program to tell the user to rewrite that number. I don't want the program to just end with a error. How can I do that?

like image 670
Average kid Avatar asked Jan 31 '26 15:01

Average kid


2 Answers

while True:
   n = int(input("enter a number between 0 and 100: "))
   if 0 <= n <= 100:
      break
   print('try again')

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

like image 71
NPE Avatar answered Feb 02 '26 07:02

NPE


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 in range(total):
    while True:
        n = int(input("Enter a test score >> "))
        if n in range(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:

def getTestScore():
    while True:
        n = int(input("Enter a test score >> "))
        if n in range(0, 101):
            return n

for i in range(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:

def getTestScore():
    while True:
        try:
            n = int(input("Enter a test score >> "))
        except ValueError:
            pass
        else:
            if n in range(0, 101):
                return n
like image 38
abarnert Avatar answered Feb 02 '26 07:02

abarnert