You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python石头剪刀布游戏添加计分系统后触发索引越界错误求助

石头剪刀布游戏索引越界问题修复

问题根源

触发IndexError: list index out of range的原因是这段代码:

comp_number=random.randint(0,3)

random.randint(a, b)会生成包含a和b的随机整数,所以这里可能输出0、1、2、3四个值。但你的options列表只有3个元素,合法索引是0、1、2,当随机到3时,就会超出列表范围报错。你误以为是系统选中rock时出错,只是刚好随机到3时的巧合。

修复方法

有两种可靠的修复方式:

  1. 缩小随机数范围到合法索引区间:
comp_number=random.randint(0,2)
  1. 更简洁的方式:用random.choice()直接从列表中选取元素,无需手动处理索引:
comp_choice=random.choice(options)

修正后的完整代码

import random
score=0
options=["rock","paper","scissor"]
while True:
    our_input=input("Please select between rock/paper/scissor or q to quit ").lower()
    if our_input=="q":
        break
    if our_input in options:
        print("you chose "+our_input)
    else:
        print("Please enter a valid input")
        # 无效输入时跳过后续逻辑,避免不必要的执行
        continue

    comp_choice=random.choice(options)
    print("comp chose "+comp_choice)

    if comp_choice=="rock" and our_input=="paper":
        print("You won!")
        score+=1
        print(score)

内容的提问来源于stack exchange,提问作者123456

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 14:40:50