如何循环try-except代码直至解决输入异常及负数错误?
Fixing the Loop for Valid Cat Count Input
Hey there! Let's tweak your code so it keeps prompting the user until they enter a valid non-negative integer. The core idea is using an infinite loop that only exits once we get a valid input. Here's how to make it work:
Modified Code
while True: print('How many cats do you have?') numCats = input() try: # Convert input to integer once, reuse it for all checks cat_count = int(numCats) if cat_count >= 4: print('That is a lot of cats.') break # Exit loop since input is valid elif cat_count < 0: print("You can't have negative cats, dumbo") # No break here—loop restarts to ask again else: print('That is not that many cats') break # Exit loop for valid non-negative input except ValueError: print('You did not enter a number') # No break here—loop restarts to ask again
How This Works
while True: This sets up an infinite loop that runs nonstop until we hit abreakstatement. It’s perfect for forcing the user to keep trying until they provide valid input.- Single Integer Conversion: We convert the input string to an integer once inside the
tryblock, instead of repeating the conversion in each condition check. This is cleaner and more efficient. - Handling Invalid Cases:
- If the user enters non-numeric text (like "six"), the
ValueErrortriggers, we print an error message, and the loop starts over without exiting. - If the user enters a negative number, we call out the mistake but don’t exit the loop—giving them another shot to enter a valid number.
- If the user enters non-numeric text (like "six"), the
- Exiting the Loop: Only when the user enters a valid non-negative integer (0 or higher) do we print the appropriate response and use
breakto stop the loop.
内容的提问来源于stack exchange,提问作者Lse Library
相关产品推荐
相关产品推荐

