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

为何无法检查列表中是否包含指定数字?代码报错求助

问题根源

你把列表rolls_list的类型给覆盖了:

  • 一开始你定义rolls_list = []是个空列表,但循环里用rolls_list = random.randint(1,6)把它改成了单个整数。
  • 后面执行if 1 in rolls_list时,Python没法在整数里查找元素,直接就报错了——in只能用来遍历列表、字符串这类可迭代对象,整数不行。
修正后的代码
import random  # 原代码没导入random模块,不加会先报名称错误

player_turn = True
player_score = 0
enemy_score = 0
rolls_list = []
tempScore = 0

if player_turn:
    user_input = int(input("How many times do you want to roll the dice? (0 - 10)"))
    for i in range(user_input):
        roll_num = random.randint(1,6)
        rolls_list.append(roll_num)  # 用append把每次掷的结果加到列表里,而不是覆盖列表
        print(roll_num)
        tempScore += roll_num
    if 1 in rolls_list:
        tempScore = 1
    player_score = tempScore
补充说明
  • 原代码漏了import random,必须加上,不然连random.randint都调用不了。
  • 如果你把if语句移到循环里,逻辑会变成“只要掷出1就立刻把tempScore改成1”,和你原本“全部掷完后检查有没有1,再改总分”的逻辑不一样,按需调整就行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 18:52:36