You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 (like 7).
  • input() always returns a string value—even if the user types 7, 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:

  1. Added import random—your original code would crash without this, since you're using random.randint.
  2. Replaced the second if with an else—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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 22:12:49