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

Python随机掷骰子运势程序每次仅输出首个结果问题求助

错误排查

  • 变量名误用:生成的1-6随机数存储在变量answers中,但后续所有条件判断都使用了初始赋值为True的变量answer。Python中布尔值True等价于整数1,所以每次都会触发第一个answer == 1的分支,输出固定结果。
  • 未定义函数调用:代码末尾的roll()没有提前定义,程序运行到此处会抛出名称错误。
  • 循环条件可优化:while answer的写法等价于死循环,可直接简化为while True更易读。

修正后代码

import random 
import sys 

while True:
    question = input("Roll the di to get your fortune (press enter directly to exit): ")

    if question == "":
        sys.exit()

    answer = random.randint(1,6) 
    if answer == 1: 
        print("You will get a new friend. ")
    elif answer == 2:
        print("You will go to disneyland. ")
    elif answer == 3: 
        print("You will receive kindess.. ")
    elif answer == 4:
        print("Your will get a dog. ")
    elif answer == 5:
        print("You will suffer. ")
    elif answer == 6:
        print("You will have bad luck. ")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 16:36:04