-2

I'm in the middle of writing some simple Python code, however, I'm still a novice and I've encountered a problem that I have been unable to solve.

name = raw_input("What is your name? ")

maths = int(input("Enter your maths test result: "))
psychology = int(input("Enter your psychology test result: "))
economics = int(input("Enter your economics test result: "))
IT = int(input("Enter your IT test result: "))
religion = int(input("Enter your religion test result: "))
biology = int(input("Enter your biology test result: "))
average = (maths + psychology + economics + IT + religion + biology)/6
print "Your average test score is: ", average
minimum = min(maths, psychology, economics, IT, religion, biology)
print "Your lowest score is: ", minimum
maximum = max(maths, psychology, economics, IT, religion, biology)
print "Your highest score is: ", maximum

The code above allows the user to enter their test results, and returns their average, minimum and maximum scores. However, I need to create a range so that users cannot enter any results below 0 or above 100, although, I'm unsure how to do so even after trying to find out by myself or online.

I'd appreciate any help regarding my issue, thanks.

C.NC
  • 3
  • 1
  • 2

1 Answers1

1

create a function that check for the user input that return only when the input is valid, like:

def ask_user(msj, start=0, end=100):
    while True:
        try:
            n = int(raw_input(msj))
            if start <= n <= end:
                return n
        except ValueError:
            pass
        print("invalid input, try again")

and use instead of int(input(...))

Copperfield
  • 8,131
  • 3
  • 23
  • 29