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

循环头部使用布尔变量作为条件的猜数字游戏实现求助

How to Implement a Loop Header with a Boolean Variable in Your Number Guessing Game

Your Question

I'm working on a number guessing game project, and one requirement is to write a loop header using a boolean variable as the condition—I don't understand this instruction. Here's my current code:

question=input("Do you want to set the integer that shall be guessed? (Yes/No)")
if question == "yes":
    number=int(input("Integer that shall be guessed: "))
elif question == "no":
    number=58
else:
    print ("Please enter yes or no")
guess=int(input("Enter a integer from 1 to 100! "))
guess_number=1
while guess != number:
    if guess < number:
        print("too small")
        guess=int(input("Enter a integer from 1 to 100! "))
        guess_number=guess_number+1
    elif guess > number:
        print("too large")
        guess=int(input("Enter a integer from 1 to 100! "))
        guess_number=guess_number+1
print("Correct!")
print(f'Number of attempts: {guess_number}')

I don't know how to meet the requirement of writing a loop header with a boolean variable as the condition. Please help!


Let's Break This Down

First, the requirement is asking you to replace the direct comparison in your while loop (right now you’re using guess != number) with a dedicated boolean variable that controls whether the loop keeps running. This makes your code more readable and flexible—you can easily stop the loop for other reasons later if you want, without messing with the guess/number comparison.

Modified Code That Meets the Requirement

Here's a revised version of your code that uses a boolean variable for the loop condition, plus some small improvements to clean up the logic:

# Make input case-insensitive and handle invalid choices better
question = input("Do you want to set the integer that shall be guessed? (Yes/No)").lower()
number = None

if question == "yes":
    number = int(input("Integer that shall be guessed: "))
elif question == "no":
    number = 58
else:
    print("Please enter yes or no")
    exit()  # Exit early if input is invalid to avoid errors

# Initialize a boolean variable to control the loop
game_active = True
attempt_count = 0

# Loop uses the boolean variable as its condition
while game_active:
    guess = int(input("Enter an integer from 1 to 100! "))
    attempt_count += 1
    
    if guess < number:
        print("Too small!")
    elif guess > number:
        print("Too large!")
    else:
        print("Correct!")
        game_active = False  # Toggle the boolean to stop the loop

print(f'Number of attempts: {attempt_count}')

Key Changes Explained

  • Boolean Variable for Loop Control: We created game_active = True to start the game in a running state. The while loop now checks this variable directly instead of comparing guess and number.
  • Cleaner Loop Exit: When the user guesses correctly, we set game_active = False—this signals the loop to stop on its next check.
  • Streamlined Input & Counting: Moving the guess input inside the loop eliminates redundant code (you don’t have to repeat the input line twice), and incrementing the attempt count right after the guess makes the logic clearer.
  • Case-Insensitive Input: Adding .lower() to the first input means users can type "YES", "Yes", or "yes" and it will work.
  • Early Exit for Invalid Input: The exit() call stops the program if the user enters something other than yes/no, preventing errors later when number would be undefined.

This approach not only meets the requirement but also makes your code more maintainable and easier to read.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 17:32:49