Python程序正负整数输入校验:解决.isdigit()不支持负数的问题
I get it, those string methods like isdigit() and isnumeric() can be frustrating here—they only recognize non-negative digits, so any input with a minus sign gets rejected immediately. Let's walk through two solid ways to fix this:
Method 1: Try-Except Block (Recommended)
The most Pythonic way to handle this is to attempt converting the input to an integer directly, and catch the error if it fails. This handles all valid integer cases (positive, negative, zero) automatically, even if someone accidentally adds a plus sign.
Here's how to adjust your code:
while True: lowest_num_input = input("What would you like the lowest possible number to be? ") try: lowest_num = int(lowest_num_input) break # Exit the loop if conversion succeeds except ValueError: print("Please only enter a valid integer (positive or negative).") # Now you can use lowest_num as an integer in your program print(f"Got it, your lowest number is {lowest_num}")
Why this works:
- If the input is a valid integer (like
-5,10,0),int(lowest_num_input)will convert it without issues, and we break out of the loop. - If the input is a string, decimal, or garbage text (like
"abc","3.14"), aValueErroris thrown, and we prompt the user again.
Method 2: String Format Check
If you prefer to validate the string before converting, you can check if it meets the integer format rules:
- Either it's all digits (positive/zero), or
- It starts with a
-followed by at least one digit (negative)
Here's the code for this approach:
lowest_num = input("What would you like the lowest possible number to be? ") while not (lowest_num.isdigit() or (lowest_num.startswith('-') and lowest_num[1:].isdigit())): lowest_num = input("Please only enter a valid integer (positive or negative): ") # Convert to integer once validated lowest_num = int(lowest_num) print(f"Got it, your lowest number is {lowest_num}")
Note:
- This doesn't handle inputs with a plus sign (like
+7) unless you add an extra check forlowest_num.startswith('+') and lowest_num[1:].isdigit(). - You also need to make sure the input isn't just a single
-(thelowest_num[1:].isdigit()takes care of that, since an empty string after-will fail the check).
Quick Fix for Your Original Code
Your original code had a .lower() call which was unnecessary (since numbers don't have case), so removing that and replacing the validation with one of the above methods will solve your problem.
内容的提问来源于stack exchange,提问作者MacKenzie Richards

