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:
- 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. - Guess values aren't updated in the loop: When you call
getUserGuess()inside theelseblock, you don't save the new guess (or new random number) to yourrandgvariables. So the loop keeps checking against the first guess and first random number—making theelifcondition 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
guessCountcorrectly when a wrong guess is made. - Fixed variable scoping: No more stale
randgvariables—we usetarget_numanduser_guesswhich 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
相关产品推荐
相关产品推荐

