如何简化Python中正整数输入的验证逻辑?
Simplified & Fixed Version of Your
enterReadings Function Hey there! Let's start by pointing out a critical bug in your original code first—right after you finish validating the user's input, you overwrite readingsCount to 0, which means all that validation work goes to waste, and your function will always return 0. Oops!
Beyond fixing that bug, we can absolutely simplify the validation logic to make it cleaner and more concise. Here's how:
First, the Fixed & Simplified Core Version
def enterReadings(message): while True: try: readingsCount = int(input(message)) # If input is valid, return immediately instead of using break if readingsCount > 0: return readingsCount # If not positive, show error and loop again print("Please enter a positive integer") except ValueError: # Catch non-integer inputs and show same error print("Please enter a positive integer")
Even Cleaner: Avoid Repetition with a Reusable Error Message
To follow the DRY (Don't Repeat Yourself) principle, we can extract the error message into a variable so we don't type the same string twice:
def enterReadings(message): error_prompt = "Please enter a positive integer" while True: try: count = int(input(message)) if count > 0: return count print(error_prompt) except ValueError: print(error_prompt)
Key Improvements Over Your Original Code:
- Fixed the return value bug: No more overwriting the valid input to 0
- Removed redundant
continueandbreak: Instead, we return as soon as we get a valid input, which makes the flow more intuitive - Eliminated useless post-loop logic: The
if readingsCount > 0check was doing nothing in your original code, so we got rid of it entirely - Optional: Reduced code duplication: The second version uses a single variable for the error message, making it easier to update later if needed
内容的提问来源于stack exchange,提问作者r0llie
相关产品推荐
相关产品推荐

