Python列表能否作为if条件?猜数字游戏输入校验求助
Hey there! Let's work through fixing your number guessing game. I see a couple of key issues that are causing all inputs to be marked invalid, plus some other tweaks to make the logic smooth.
Why All Inputs Are Marked Invalid
Your check if guess != acceptable is comparing a single string (the user's input) to an entire list of strings. A string will never equal a list, so this condition is always True—hence every input gets rejected. Instead, you need to check if the input isn't present in the acceptable list using the not in operator:
if guess not in acceptable:
Can You Use a List as an If Condition?
Absolutely! But how you use it matters:
- If you write
if acceptable:, it will evaluate toTrueas long as the list isn't empty. - For your use case (checking if a value is in the list), you need
in/not into check membership, which is exactly what we fixed above.
Fixed Full Code
import random print('Hello. What is your name?') yourName = input() # 获取用户姓名 solution = random.randint(1, 20) print(f'Well, {yourName}, I am thinking of a number between 1 and 20.') # 用列表推导式生成可接受的输入,不用手动逐个编写 acceptable = [str(num) for num in range(1, 21)] def game(): global solution for attempts in range(1, 6): print(f'Take a guess. You have {6 - attempts} attempt(s) remaining') # 循环获取输入,直到得到有效内容 while True: guess = input().strip() if guess not in acceptable: print("That is not a valid answer! Please enter an integer between 1 and 20.") else: guess_int = int(guess) break # 输入有效,跳出循环 # 直接在当前函数处理猜数字逻辑,避免变量作用域问题 if guess_int == solution: print(f'You guessed it! It took you {attempts} attempt(s)') playAgain() return # 结束当前游戏流程 elif guess_int < solution: print('Your guess is too low. Try again.') else: print('Your guess is too high. Try again.') # 用完所有尝试次数仍未猜对 print(f'Game over! The number I was thinking of was {solution}') playAgain() # 选择重新开始游戏,生成新数字 def playAgain(): global solution print('Play again? Y/N') # 校验重新开始的输入,只接受Y/N(不区分大小写) while True: play_choice = input().strip().upper() if play_choice in ['Y', 'N']: break print("Please enter 'Y' or 'N'.") if play_choice == 'Y': print(f'Okay, {yourName}, I have another number between 1 and 20.') solution = random.randint(1, 20) game() else: print('Thanks for playing!') # 启动游戏 game()
Key Fixes & Improvements
- Input Validation: Replaced the incorrect list comparison with
not into properly check valid inputs, and added a loop to keep asking for input until it's valid. - Variable Scope: Removed separate
moveonandendofgamefunctions to handle logic directly ingame()—this avoids issues where functions couldn't access variables likeguessorattempts. - Type Conversion: Converted valid input strings to integers so we can properly compare them to the integer
solution. - Simplified Valid List: Used a list comprehension to generate valid input strings instead of writing each one manually.
- Robust Play-Again Prompt: Added validation for the play-again choice to ensure only 'Y' or 'N' (case-insensitive) are accepted.
- Readable Formatting: Used f-strings for cleaner, more readable string formatting instead of concatenating with
+.
内容的提问来源于stack exchange,提问作者Shriniket S
相关产品推荐
相关产品推荐

