如何用随机数生成器(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
相关产品推荐
相关产品推荐

