验证函数问题求助:实现1-10分数输入校验并用于列表追加
Fixing Your Score Validation Function
Hey there! Let's break down the issues in your current code and get that validation function working properly. Right now, it has a few bugs that are keeping it from correctly checking scores between 1 and 10—let's fix them one by one:
Key Issues in Your Original Code
- Unused parameters: The
goodNumandscoreparameters are immediately overwritten in the function, so they don't serve any purpose. We can remove them since you're collecting input directly inside the function. - Critical assignment bug:
goodNum == Trueis a comparison operator, not an assignment. This meansgoodNumnever actually gets set toTrue, so your loop will run forever even with a valid score. You need to usegoodNum = Truehere. - Incomplete error handling: If the user enters a non-numeric value twice, your code will try to compare a string to an integer (e.g., checking if
"abc" > 1), which throws an error. We need to ensurescoreis always an integer before checking its range. - Incorrect range check: Your condition
score > 1 and score < 11excludes 1 and 10. Since you want scores between 1 and 10 (inclusive), usescore >= 1 and score <= 10instead. - Redundant input prompts: You're repeating the
raw_inputcall in theexceptblock. We can refactor this to keep the input prompt in one place inside the loop for cleaner code.
Fixed Code (Python 2 Version)
def validation(): goodNum = False while not goodNum: score_input = raw_input("Please enter a valid score between 1 and 10: ") try: # Convert input to integer score = int(score_input) # Check if score is within the valid range if 1 <= score <= 10: goodNum = True else: print("Invalid score! Must be between 1 and 10.") except ValueError: # Handle non-integer inputs print("Invalid input! Please enter a whole number.") # Return the valid score to use for appending to your list return score
Fixed Code (Python 3 Version)
If you're using Python 3, replace raw_input with input (since raw_input was renamed to input in Python 3):
def validation(): goodNum = False while not goodNum: score_input = input("Please enter a valid score between 1 and 10: ") try: score = int(score_input) if 1 <= score <= 10: goodNum = True else: print("Invalid score! Must be between 1 and 10.") except ValueError: print("Invalid input! Please enter a whole number.") return score
How to Use It
Now you can call this function to get a valid score and append it to your list like this:
score_list = [] valid_score = validation() score_list.append(valid_score)
内容的提问来源于stack exchange,提问作者Finn Alan Fuller
相关产品推荐
相关产品推荐

