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:
        try:
            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)
print(num_test)

The function loops until the correct input has been received.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.