获取用户输入菜单索引时触发TypeError,该如何解决?
解决列表索引类型错误并实现菜单选择功能
错误原因
你碰到的TypeError是因为input()获取的用户输入默认是字符串类型,而列表的索引必须是整数或切片,直接用字符串当索引自然会报错。另外你代码里的index变量未定义,应该用user_choice替代。
基础修复版本
先把输入转为整数,修正未定义的变量问题:
menu = ["pasta", "pizza", "salad"] # 将输入的字符串转为整数类型 user_choice = int(input("Enter the index of the item: ")) # 替换未定义的index为user_choice message = f"You chose index {user_choice}: {menu[user_choice]}." print(message)
健壮性优化版本
上面的代码如果用户输入非数字或超出索引范围仍会报错,建议加上菜单提示和异常处理,让程序更易用:
menu = ["pasta", "pizza", "salad"] # 先展示菜单及对应索引,让用户明确可选范围 print("Available menu indexes:") for idx, item in enumerate(menu): print(f"{idx}: {item}") while True: try: user_choice = int(input("\nEnter the index of the item: ")) # 检查索引是否在有效范围内 if 0 <= user_choice < len(menu): break else: print(f"Please enter an index between 0 and {len(menu)-1}!") except ValueError: print("Please enter a valid number!") message = f"You chose index {user_choice}: {menu[user_choice]}." print(message)
优化说明
- 用
enumerate()遍历列表,自动生成索引和对应项,方便用户查看可选内容 while True循环保证用户输入有效内容后才继续执行try-except捕获非数字输入的异常,给出友好提示- 增加索引范围检查,避免出现索引越界错误
内容的提问来源于stack exchange,提问作者amit rai
相关产品推荐
相关产品推荐

