Start New Discussion within our Software Development Community

Python 2.6.1:

How would I write a user input validation statement
scores < 0 or scores > 100
print error message and ask for input again?

Where would I place it, in the below code?

num_test = raw_input("How many test would you like to average? ")
    scores = []
    for i in xrange(int(num_test) ):
        scores.append(input("score "+str(i)+":"))

Generally you write a function for that, something like this:

# check the input of an integer between given limits

def check_input(low, high):
    check the input to be an integer number within a given range
    prompt = "Enter an integer number between %d and %d: " % (low, high)
    while True:
            a = int(raw_input(prompt))
            if low <= a <= high:
                return a
        except ValueError:
            print("Hey, I said integer number!")

# test the function ...
# expecting an integer number between 1 and 50
num_test = check_input(1, 50)

The function loops until the correct input has been received.

This question has already been answered. Start a new discussion instead.