Python中条件为真时首个if语句为何未执行?输入正确数字仍提示错误问题
Hey Josh, I see exactly what's going on here! The issue boils down to a type mismatch between your player's guess and the computer's number.
Let me break it down simply:
random.randint(1, 10)spits out an integer (like7).input()always returns a string value—even if the user types7, it gets stored as"7"(with quotes, essentially).
When you compare playerGuess == computerNum, you're checking if a string equals an integer. Python doesn't treat these as the same thing, so that first if statement never triggers, even when the digits match perfectly.
Fixed Code
The quick fix is to convert the user's input to an integer right when you get it. Here's your updated, working code:
import random # Don't forget this! Your original code would throw an error without importing the random module def start(): computerNum = random.randint(1, 10) print(computerNum) # Convert input to integer immediately playerGuess = int(input("Enter your guess: ")) if playerGuess == computerNum: print("You got it! The number was " + str(computerNum)) else: # Swapped to else for cleaner logic (no need for a second if check) print("You are wrong, the number is " + str(computerNum)) startPlay = input("Would you like to play the game? ").lower() if startPlay == 'yes': start()
Quick Extra Tips
I added two small quality-of-life tweaks too:
- Added
import random—your original code would crash without this, since you're usingrandom.randint. - Replaced the second
ifwith anelse—it's more efficient and readable, because if the first condition isn't true, the else will always run.
If you want to handle cases where the user enters non-numeric text (like "abc"), you could add a try-except block to catch the ValueError, but that's a nice-to-have for later!
内容的提问来源于stack exchange,提问作者Josh

