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

Python中while逻辑运算符导致程序无响应问题求助

问题分析与解决

Hey there! Let's figure out why your code is acting up—you're off to a great start with your first Python project, so let's break this down simply.

The Core Issue: Conflicting Nested while Loops

Your outer while number != guess: loop is clashing with the two inner while loops you wrote for checking high/low guesses. Here's what's happening:

  • When you enter the outer loop (because your first guess was wrong), the inner while guess < number or while guess > number will take over and keep asking for input until your guess is no longer too low/high. But once that inner loop finishes, the outer loop will kick back in again, re-checking number != guess and incrementing count unnecessarily. This creates messy, redundant logic that can lead to unexpected behavior.
  • Also, that if guess == number: line inside the outer loop is completely useless—since the outer loop only runs when number != guess, this condition will never be true.

Why It Works When You Delete Those Lines?

When you remove the outer while and count = count +1, your code uses the inner loops directly, and the initial if guess == number: can trigger if you get it right on the first try. That's why you see proper feedback then. But even that version has a flaw: if you guess too low, then too high, it won't loop back to the "too high" check automatically.

Fixed Version of Your Code

Here's a cleaner approach using a single while loop to handle all cases, plus proper feedback for the number of tries:

import random
number = random.randint(1, 10)
count = 1
guess = int(input("Enter your guess between 1 and 10 : "))

while number != guess:
    count += 1
    if guess < number:
        guess = int(input("Too low :( Guess again ! : "))
    else:
        guess = int(input("Too high :( Guess again ! : "))

# Once we exit the loop, we know the guess is correct
print(f"That is my number ! You got it in {count} tries!")

This way, we only loop until the guess matches, increment the count each time we retry, and give clear feedback for high/low guesses every step of the way.

内容的提问来源于stack exchange,提问作者Dominik Podlipniak

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:08:38