Python3中isdigit语法错误问题及猜数字代码功能优化求助
Hey there! Let's work through your code issues one by one and add that "ur close" feature you want.
First: Fix the Syntax Error
The line if n not n.isdigit(): throws a syntax error because of incorrect logic structure. The right way to check if the input isn't a valid digit is if not n.isdigit() — the not keyword needs to come directly before the method call to negate its boolean result.
Second: Fix Hidden Type Mismatch Error
Your input n is a string (from the input() function), but you're trying to compare it directly to the integer x (generated by random.randint()). This will trigger a TypeError since you can't compare strings and integers directly. After confirming the input is a digit, convert it to an integer with n = int(n).
Third: Add the "Ur Close" Feature
To check if the guess is within ±20 of the target number, calculate the absolute difference between the guessed number and x using abs(n - x). If that difference is ≤20, print your "ur close" message. Make sure to do this after converting n to an integer but before checking if it's higher or lower than x.
Bonus: Adjust Input Check Order
Right now, if you enter "Q", the code first tries to check if it's in the valid number range (which will fail because "Q" is a string). Let's reorder the checks so we first handle the quit command, then validate if it's a digit, then check the range. That makes the code flow more logical.
Here's the Modified Code
import random x = random.randint(0, 100) i = 0 while True: n = input("sheitanet ricxvi an Q gamosvlistvis: ") # First check if user wants to quit if n == "Q": print("Bye Bye!") break # Check if input is a valid digit if not n.isdigit(): print("gtxovt sheitanot ricxvi an Q") continue # Convert input to integer now that we know it's a digit n = int(n) # Check if number is within 0-100 range if n >= 101 or n < 0: print("sheikvanet ricxvi 0 dan 100 is shualedshi!!!!") continue # Add the "ur close" check if abs(n - x) <= 20: print("ur close") # Check if guess is correct if n == x: print("Tqven gamoicanit chafiqrebuli ricxvi!", i, "Cdashi") break elif n < x: print("tqveni shetanili ricxvi naklebia chafiqrebul ricxvze") i += 1 elif n > x: print("tqveni ricxvi metia chafiqrebul ricxzze") i += 1
Key changes explained:
- Fixed the
isdigit()check syntax to use proper negation - Reordered input checks to handle the quit command first
- Added
n = int(n)to convert valid digit inputs to integers for numeric comparisons - Added the
abs(n - x) <= 20condition to show the "ur close" hint - Ensured invalid inputs (non-digit, out of range) don't increment the attempt counter
i
内容的提问来源于stack exchange,提问作者Sandro Gamrekelashvili

