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

如何让猜4位数字程序猜对后停止询问并显示"You Win!"

Fixing Your 4-Digit Guess Game Termination Issue

Hey there! Let's sort out why your guess game isn't wrapping up and showing "You Win!" when the user nails the 4-digit code. I'll walk through the problem with your original setup, then share a fixed version with explanations.

First, Let's Break Down the Core Issues

From the code snippet you shared plus your problem description, here's what's likely going wrong:

  • Missing/Misconfigured Loop: Your code probably lacks a persistent loop to keep asking for guesses, or the loop's termination logic is broken. Even if you tried break, it might not have been placed in the right spot to exit the game.
  • Clunky Digit Comparison: Using separate variables (n1, n2, etc.) makes checking for a perfect match error-prone—it's easy to miss a condition or miswrite a comparison.
  • No Explicit Win Trigger: There's no clear, actionable check that fires when all 4 digits are correct, leading to the game never ending even when the guess is perfect.

Fixed Code with Proper Termination

Here's a revised version that works as intended, with comments explaining key changes:

import random

# Generate a 4-digit secret code (using a list makes comparisons way cleaner)
secret_code = [random.randint(0, 9) for _ in range(4)]
wrong_guesses = 0

print("I'm thinking of a 4-digit code. Guess what it is!...")

# Use an infinite loop that only exits when the user wins
while True:
    # Get and validate user input to avoid crashes from bad entries
    user_guess = input("Enter your 4-digit guess: ")
    if len(user_guess) != 4 or not user_guess.isdigit():
        print("Oops! Please enter a valid 4-digit number (no letters or short/long entries).")
        continue
    
    # Convert the input string into a list of integers to match our secret code
    guess_digits = [int(digit) for digit in user_guess]
    
    # Check if the guess is a perfect match
    if guess_digits == secret_code:
        print("You Win!")
        break  # This breaks out of the infinite loop immediately when correct
    
    # If wrong, increment the count and give optional feedback
    wrong_guesses += 1
    # Optional: Tell the user how many digits are in the right place
    correct_in_place = sum(1 for g, s in zip(guess_digits, secret_code) if g == s)
    print(f"Nope! You have {correct_in_place} digits in the right spot. Total wrong guesses: {wrong_guesses}")

Key Fixes Explained

  • Infinite Loop with Break: The while True loop runs until we hit the break statement, which only triggers when the user's guess matches the secret code. This ensures the game keeps going until the win condition is met.
  • Cleaner Comparison: Using a list for the secret code lets us compare the entire guess in one line (guess_digits == secret_code) instead of writing four separate and conditions (which is easy to mess up).
  • Input Validation: We check that the user enters exactly 4 digits, so the game doesn't crash if someone types letters or a shorter/longer number.
  • Explicit Win Logic: As soon as the guess is correct, we print "You Win!" and exit the loop—no more hanging after a correct guess.

If you tried break before but it didn't work, it was probably because either:

  • The win condition wasn't being triggered (maybe a typo in comparing n1/n2/etc.), or
  • The break wasn't inside the correct block of code to exit the main game loop.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:27:46