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

如何用随机数生成器(RNG)为颜色分配数字区间?Python实现咨询

实现方案

这里给你几种实用的实现方案,都能在原代码基础上完成需求:

1. 基础if-else判断(直观易懂)

直接在每次生成随机数后,用if-else判断区间并输出对应颜色,和原逻辑完美整合:

from random import randint

x = randint(1, 1000)
i = 1
# 第一次生成随机数后先判断输出颜色
if 1 <= x <= 500:
    print("red color")
else:
    print("white color")

while x != 1:
    i += 1
    x = randint(1, 1000)
    # 每次生成新的随机数都判断输出
    if 1 <= x <= 500:
        print("red color")
    else:
        print("white color")

print(f"直到生成1的次数: {i}")

2. 三元表达式简化写法

如果想让代码更简洁,可以用Python的三元表达式把判断逻辑压缩成一行,效果和if-else完全一致:

from random import randint

x = randint(1, 1000)
i = 1
print("red color" if 1 <= x <= 500 else "white color")

while x != 1:
    i += 1
    x = randint(1, 1000)
    print("red color" if 1 <= x <= 500 else "white color")

print(f"直到生成1的次数: {i}")

3. 封装函数(便于复用和维护)

如果后续可能需要调整区间规则或颜色值,把判断逻辑封装成函数会更方便维护:

from random import randint

def get_color(num):
    return "red color" if 1 <= num <= 500 else "white color"

x = randint(1, 1000)
i = 1
print(get_color(x))

while x != 1:
    i += 1
    x = randint(1, 1000)
    print(get_color(x))

print(f"直到生成1的次数: {i}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 14:30:39