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

如何修正Python猜数字代码的随机数生成逻辑?

Fixing Your Number Guessing Game Logic

Got it, let's sort out this number guessing game for you! The core issue here is that you're generating a new random number every single time the loop runs—so every time you make a guess, the target answer changes. That's why you could never actually guess right (unless you got super lucky with the new random number on the same try!).

Here's the revised code that keeps one fixed random number per game session, lets you guess as many times as needed, and properly handles the exit command:

import random

# Generate the target number ONCE before the game loop starts
answer = random.randrange(1, 100)

guess = ''
while guess != 'exit':
    guess = input('Enter a number between 1 and 100 or enter exit to exit: ')
    
    # Handle exit first to simplify flow
    if guess == 'exit':
        print('Game closed')
        break
    
    # Validate input is a valid digit
    if not guess.isdigit():
        print('Your guess was not a digit, try again')
        continue
    
    # Convert guess to integer for proper numeric comparison
    guess_num = int(guess)
    
    # Compare guess to the fixed answer
    if guess_num == answer:
        print('Correct! You won!')
        # Optional: Uncomment below to auto-start a new round after winning
        # answer = random.randrange(1, 100)
        # print('Let\'s play another round!')
    elif guess_num > answer:
        print('Too high, try again')
    else:
        print('Too low, try again')

Key Adjustments Explained:

  • Moved random number generation outside the loop: Now answer is set once when the game starts, so it stays consistent through all your guesses until you exit (or start a new round if you enable the optional code).
  • Fixed type comparison bugs: Instead of converting the answer to a string, I convert valid user guesses to integers. This avoids weird issues like string '10' being considered "less than" '9' (since strings compare lexicographically, not numerically).
  • Streamlined input handling: Checking for 'exit' first, then validating input, makes the code flow more intuitive. Using continue after invalid input skips the rest of the loop iteration and jumps straight to asking for a new guess.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:28:15