Python运行random.choice代码触发IndexError列表索引越界报错
报错根因
你遇到的索引越界问题和随机选值逻辑无关,是两个代码逻辑漏洞共同导致的:
- 你用了3个独立的
if做分支判断,分支之间不是互斥关系,匹配到第一个分支执行完代码后,程序还会继续执行后面两个if的判断逻辑 - 你在匹配到的分支里执行了
questions.remove(q_choice),会把当前选中的问题从列表里删掉,列表长度从3变成2,此时合法的列表索引只剩0和1。等程序跑到第三个if判断访问questions[2]时,这个索引已经不存在了,就会抛出IndexError: list index out of range。
实际触发流程示例:
- 随机选中列表第0位的问题「What is your favourite movie?」
- 进入第一个
if分支,接收用户输入后执行remove操作,此时questions只剩2个元素,最大有效索引为1 - 程序没有跳出分支判断,继续执行第二个
if,判断q_choice是否等于当前的questions[1](原列表第三个问题),不匹配就跳过 - 程序继续执行第三个
if,尝试访问questions[2],但当前列表长度只有2,直接触发索引越界报错
修复方法
把后两个独立的if改成elif,让三个分支变成互斥关系:只要匹配到一个分支执行完,就不会再跑后面的判断逻辑,从根源上避免访问删除元素后的无效索引。
修复后的完整代码如下:
import random def do_question(): questions = ["What is your favourite movie?", "What is your name?", "What are your hobbies?"] q_choice = random.choice(questions) if q_choice == questions[0]: inter = input(f"{q_choice}") questions.remove(q_choice) print("Amazing! My favourite movie is Pirates Of The Caribbean: The Curse Of The Black Pearl") elif q_choice == questions[1]: inter = input(f"{q_choice}") questions.remove(q_choice) print(f"Glad to talk to you, {inter}. I'm PYchatter.") elif q_choice == questions[2]: inter = input(f"{q_choice}") questions.remove(q_choice) print("Wow! Those are nice hobbies you have. My hobby is talking to people like I am doing right now.")
补充优化建议:如果后续你需要循环调用这个函数实现不重复抽题的效果,不要把questions列表定义在函数内部,否则每次调用函数都会重置成3个问题的完整列表,remove操作不会生效。
内容的提问来源于stack exchange,提问作者Suriya
相关产品推荐
相关产品推荐

