简体   繁体   中英

Python Input Validation with multiple variables…simplified?

First, I've searched this site, a lot, and found other posts about this topic, even the same assignment I'm working on, so the code is very similar... However, there are a few things slightly different. I'm taking this course, using "Starting out with Python, 4th edition," and my assignment is from chapter 5, "15. Test Average and Grade." I've got the code written for everything except input validation, which my instructor insists we use, though we are only supposed to use coding techniques the book has covered up to this point: no lists, tuples, dictionaries, lambda, etc... Which makes most of the examples I've found online (and on this site) for input validation useless, as I can't figure them out and couldn't use them if I wanted to. I've reached out to the instructor for help (online course), but haven't received any reply for weeks, so I'm here. The program is supposed to ask the user to input 5 test scores, find the average of the scores, assign a letter grade to each score, then display the scores w/ letter grade as well as the average. I thought it'd be easier to validate the input if I asked for the scores with a "for scores in range(1, 6)" loop, but then I don't know how to access each score input by the user to send to the determine_grade function and later to display in main (I didn't include any of that code below)... So I ended up making a variable for each score, but then I run into the problem of how to validate the input (make sure the score entered isn't less than 0 or greater than 100, or that the user has entered a number and not a letter) for each variable. I'd like to be able to write some exception handling into the code so that if the user has entered a letter instead of a number an exception isn't thrown, because my instructor has said "it's my job from now on to try to crash your program," though he hasn't gotten back to me on exactly how to implement this kind of input validation. Any help at all would be greatly appreciated, I've been struggling with this for days now, and it's seriously stressing me out.

EDIT: TypeError: input_validation() missing 4 required positional arguments: 'score2', 'score3', 'score4', and 'score5' is the error I'm getting, I know I'm doing something wrong, however, I don't know what... I feel like there is an easier way to handle input validation for multiple variables.. Since I'm still quite new at this, I've no idea whatsoever how to implement it though.

def get_scores():

score1 = input_validation(float(input('Enter the score for the first test: ')))
score2 = input_validation(float(input('Enter the score for the second test: ')))
score3 = input_validation(float(input('Enter the score for the third test: ')))
score4 = input_validation(float(input('Enter the score for the fourth test: ')))
score5 = input_validation(float(input('Enter the score for the fifth test: ')))
return score1, score2, score3, score4, score5

def input_validation(score1, score2, score3, score4, score5):
while (score1, score2, score3, score4, score5) < 0 or (score1, score2, score3, score4, score5) > 100:
    print('Score cannot be less than 0 or greater than 100!')
    (score1, score2, score3, score4, score5) = float(input('Please enter a correct test score: '))
    return score1, score2, score3, score4, score5

Your immediate error is that you've defined input_validation() to take five parameters, but you're only passing it one parameter when you call it.

It's awkward to collect input in one function and validate the input in another function, because those functions would have to be very tightly coordinated to allow for reprompting on bad input.

It's also awkward to ask for several scores at once and then validate them all at once, because what do you do if some scores are valid and some aren't? You have to either ask for all the scores again, which wastes the user's time, or you need a way of reprompting only for the invalid scores, which is needless complexity.

It might be a better design to handle just one score at a time, with all the input and validation in one place:

def input_validation(prompt):
    # keep looping until they enter a good score
    while True:
        # get the answer as a string
        answer = input(prompt)
        try:
            # convert to float
            score = float(answer)
            # if in range, we're done!  return the converted score number
            if 0 <= score <= 100:
                return score
            # otherwise out of range, print an error message and keep looping
            else:
                print('Score cannot be less than 0 or greater than 100!')
        # if the answer wasn't a number, print an error message and keep looping
        except ValueError:
            print ('That is not a test score.')

Then you can call it like this:

score1 = input_validation('Enter the score for the first test: ')
score2 = input_validation('Enter the score for the second test: ')

If you want to keep the scores in a list instead of having five separate variables:

scores = []
for i in range(5):
    scores.append(input_validation('Enter the score for test number %d: ' % i+1))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM