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

Python 生成随机数做百分比折扣计算无输出该如何解决

代码无法正常运行的原因
  • 缺失random模块导入:运行时会直接抛出模块未找到错误,程序终止无法执行后续打印逻辑
  • random.sample()返回值为列表类型:调用该方法取1个随机值时返回的是长度为1的列表而非整数,直接传入int()转换会触发类型错误,导致程序中断
  • 未定义price变量:运行时会抛出变量未定义的命名错误,程序直接退出
可正常运行的修改代码

方案1:保留sample用法调整取值逻辑

import random
# 此处price可根据实际需求修改赋值
price = 100
# 取sample返回列表的第一个元素作为随机折扣值
rndnm = random.sample(range(10, 40), 1)[0]
priceraw = int(price) - (int(price)/100*rndnm)
saleprice = str(priceraw)
print(saleprice)

方案2:使用更适配场景的randint方法(更简洁)

import random
price = 100
# randint直接返回指定闭区间内的整数随机数,无需额外取值
rndnm = random.randint(10, 39)
# 计算逻辑优化,同时保留两位小数更符合价格展示规范
priceraw = int(price) * (100 - rndnm) / 100
saleprice = f"{priceraw:.2f}"
print(saleprice)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 04:57:00