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

新手编程求助:Python恶作剧脚本随机提问功能异常

修复恶作剧宝宝提问脚本的随机选择问题

你的核心问题是不小心把存储问题列表的变量给覆盖成单个元素了,导致后续无法从完整列表里随机选问题,反而变成从单个字符串里挑字符。

看你的代码:

  • 一开始new_questions是列表,但执行new_questions = choice(new_questions)后,这个变量就变成了一个字符串(虽然初始提问这步没问题,但变量名复用埋下了隐患)
  • 到循环里,questions = choice(questions)第一次执行会把列表变成单个问题字符串,第二次再调用choice(questions)时,Python会把字符串当成字符序列来处理,随机返回单个字符,这就是你看到输入提示变成单个字符且脚本异常的原因。

修复方案很简单:不要覆盖原列表变量,用单独的变量存储每次选中的问题,修改后的代码如下:

from random import choice

# 保留原问题列表不变,用清晰的变量名区分
initial_questions = ["Where are all the dinosaurs?: ", "How are babies made?: ", "Why don't we have superpowers?: ", "Why is the sky blue?: "]
follow_up_questions = ["Well why is the sky blue then?!: ", "Why though?: ", "I still don't get it...why?: ", "OHH OKAY...no, no, wait, but...Why?: ", "WHY?!: ", "You suck at explaining things...just tell me why already.: ", "Why?: ", "What does that have to do with the sky being blue...?: ", "Yeah, I get that part, but why?: ", "Ok, why?: "]

# 用临时变量存选中的初始问题,不修改原列表
current_question = choice(initial_questions)
answer = input(current_question).strip().lower()

while answer != "just because":
    # 始终从原后续问题列表中随机选择,保证每次都有完整的选项池
    current_question = choice(follow_up_questions)
    answer = input(current_question).strip().lower()

关键修改点:

  • 给原列表换了更清晰的名字(initial_questions和follow_up_questions),避免和单个问题变量混淆
  • 用current_question临时存储每次选中的问题,原列表始终保持完整状态,这样每次循环都能从全部后续问题里随机挑选,不会出现选单个字符的情况

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 10:05:22