Python列表元素转移异常:物品已添加但提示错误文本
问题:物品转移成功后却输出"Invalid command"错误提示
我自学Python做了个小游戏,功能是让玩家查看closet列表里的物品,输入物品名称就能把它移到inventory列表里。但运行时出问题了:成功把物品加到inventory后,没显示预期的"You take the a"这类提示,反而输出"Invalid command"错误提示,找不到问题在哪,求帮忙。
附代码:
inventory=[] closet=['A','B','C'] Closetloop=False while Closetloop==False: print('Inside Your closet You have:') sleep(1) print(closet) sleep(2) print('What items do you take out? (Type "exit" to exit closet)) ClosetTake=input('You take:') sleep(1) if ClosetTake.lower()=='a': if 'A' in closet: os.system('cls') print('You take the a') res = inventory.insert(0, closet.pop(closet.index('A'))) Closetloop=False else: os.system('cls') print('Invalid command') Closetloop=False if ClosetTake.lower()=='b': if 'B' in closet: os.system('cls') print('You take the b') res = inventory.insert(0, closet.pop(closet.index('B'))) Closetloop=False else: os.system('cls') print('Invalid command') Closetloop=False if ClosetTake.lower()=='c': if 'C' in closet: os.system('cls') print('You take the c') res = inventory.insert(0, closet.pop(closet.index('C'))) Closetloop=False else: os.system('cls') print('Invalid command') Closetloop=False if ClosetTake.lower()=='exit': os.system('cls') print('You exit the closet') Closetloop=True
问题原因
核心问题是你用了多个独立的if语句,而非elif。比如当输入a时,第一个if分支会执行并输出正确提示,但代码会继续往下执行后续的if b、if c、if exit判断。因为输入不匹配这些条件,对应的else分支会被触发,重新输出"Invalid command",覆盖了之前的正确提示。
另外还有几个小问题:
while循环前有缩进错误,会直接触发语法报错- 打印exit提示的语句括号不匹配:末尾多了一个右括号
- 代码调用了
sleep和os.system('cls')但未导入对应模块 Closetloop的逻辑冗余,循环控制可以更简洁
修正后的代码
import os import time inventory = [] closet = ['A', 'B', 'C'] while True: print('Inside Your closet You have:') time.sleep(1) print(closet) time.sleep(2) print('What items do you take out? (Type "exit" to exit closet)') closet_take = input('You take:').strip().lower() time.sleep(1) if closet_take == 'a': if 'A' in closet: os.system('cls') print('You take the a') inventory.insert(0, closet.pop(closet.index('A'))) else: os.system('cls') print('Invalid command') elif closet_take == 'b': if 'B' in closet: os.system('cls') print('You take the b') inventory.insert(0, closet.pop(closet.index('B'))) else: os.system('cls') print('Invalid command') elif closet_take == 'c': if 'C' in closet: os.system('cls') print('You take the c') inventory.insert(0, closet.pop(closet.index('C'))) else: os.system('cls') print('Invalid command') elif closet_take == 'exit': os.system('cls') print('You exit the closet') break else: os.system('cls') print('Invalid command')
关键修正点
- 把多个独立
if改为elif,确保只有一个分支会执行,避免后续判断覆盖正确提示 - 修复缩进错误,
while语句不需要额外缩进 - 导入缺失的
os和time模块,修正time.sleep()的调用 - 修正打印语句的括号不匹配问题
- 用
while True配合break简化循环逻辑,去掉冗余的Closetloop变量 - 对输入做
.strip()处理,避免用户输入空格导致判断失败 - 变量名改为小写加下划线的Python规范风格
内容的提问来源于stack exchange,提问作者Jimi
相关产品推荐
相关产品推荐

