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

Python多条件While循环嵌套if语句功能异常求助

Fixing the Elif Branch Issue in Your Superhero Guess Game

Hey there! Let's break down why your elif branch isn't firing, and get your game working as intended.

What's Going Wrong?

You've got two key issues here:

  1. Random number gets regenerated every guess: Your getUserGuess() function generates a new random number every time it's called. That means when the user makes a second guess, they're trying to match a brand-new number instead of the original one from their first attempt.
  2. Guess values aren't updated in the loop: When you call getUserGuess() inside the else block, you don't save the new guess (or new random number) to your r and g variables. So the loop keeps checking against the first guess and first random number—making the elif condition impossible to hit.

Fixed Code

Here's the revised version that addresses both problems, plus some small cleanups for readability:

import random  # Move import to the top of the file (best practice)

def getUserName():
    print('Welcome to the Superhero Name Game v 2.0')
    print('Copyright \N{COPYRIGHT SIGN}2018. Alex Fraser')
    userName = input('Please enter the superhero name you wish to use. ')
    return userName

def getUserGuess():
    # Only get the user's guess here—random number is generated once outside
    userGuess = int(input('Please enter a number between 1 and 10. '))
    return userGuess

def superName(n, target_num):
    guessCount = 1
    while guessCount <= 2:  # Adjust loop condition to run exactly twice
        user_guess = getUserGuess()
        if user_guess == target_num and guessCount == 1:
            print(f'Congrats! You can use your chosen name. Your superhero name is {n}')
            return
        elif user_guess == target_num and guessCount == 2:
            print('Your superhero name is Captain Marvel.')
            return
        else:
            print(f"Wrong guess! You have {2 - guessCount} attempt(s) left.")
            guessCount += 1
    
    # If we exit the loop, both guesses were wrong
    print('All your guesses were incorrect. Sorry you do not have super powers')
    print(f'The number you were looking for was {target_num}')

# Main game flow
n = getUserName()
target_number = random.randint(1, 10)  # Generate random number ONCE here
superName(n, target_number)

Key Changes Explained:

  • Moved the random number generation: We now create the target number once at the start of the game, so the user is guessing the same number both times.
  • Split getUserGuess() to only handle input: This separates concerns and avoids regenerating random numbers accidentally.
  • Updated the loop logic: We now get the user's guess at the start of each loop iteration, and update the guessCount correctly when a wrong guess is made.
  • Fixed variable scoping: No more stale r and g variables—we use target_num and user_guess which stay updated throughout the function.

This should make your elif branch trigger correctly when the user guesses right on their second try!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:50:15