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 < numberorwhile guess > numberwill 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-checkingnumber != guessand incrementingcountunnecessarily. 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 whennumber != 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

