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

Python实现列表aList随机选中a时触发指定打印效果的问题

你的代码错误原因

  • 缩进不符合Python规范:while、if下属的代码块必须缩进4个空格,否则会触发语法错误
  • 误用不存在的属性:你通过random.choice()选出的随机元素已经存储在bList变量中,直接判断该变量的值即可,列表aList本身没有state这个属性
  • 字符串语法错误:打印内容内部包含双引号时,要么对内部双引号加转义符\,要么用单引号包裹整个字符串,否则Python会判定字符串提前结束,触发语法错误
  • 无限循环无退出条件:你写的while True如果没有break终止,会一直无限运行

可直接运行的实现代码

版本1:单次随机抽取,抽到a就打印对应内容

import random
aList = ["a", "b", "c", "d"]
selected = random.choice(aList)
print(selected)
if selected == "a":
    print("This letter is \"a\".")

版本2:循环随机抽取,直到抽到a打印后停止

import random
aList = ["a", "b", "c", "d"]
while True:
    selected = random.choice(aList)
    print(selected)
    if selected == "a":
        print("This letter is \"a\".")
        # 终止循环避免无限运行
        break

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 13:39:02