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

Python中带参数生成指定范围随机数的实现方法

Solution: Generate Random Number in Specific Ranges

Got it, let's tackle this. You want a random number that falls either in 1-9 or 15-19 (completely excluding 10-14). Here's a straightforward, readable way to build this in Python:

Step 1: Import the built-in module

First, you'll need Python's random module—no extra installations required, it comes with every standard Python setup.

Step 2: Build a reusable function

Since your valid number set is small and fixed, we can list all valid values explicitly and pick one at random. This is the easiest way to ensure you never get an unwanted number:

import random

def generate_custom_random():
    # Combine the two valid ranges into a single list
    valid_numbers = list(range(1, 10)) + list(range(15, 20))
    # Pick a random element from the valid list
    return random.choice(valid_numbers)

# Test it out!
print(generate_custom_random())

How this works:

  • range(1, 10) generates numbers 1 through 9 (since the end value in range() is exclusive)
  • range(15, 20) generates numbers 15 through 19
  • We merge these two ranges into one list of all acceptable values
  • random.choice() selects one element at random from the list, guaranteeing it's always in your desired ranges

Alternative for larger ranges (just for reference):

If your valid ranges were way bigger (and listing every element wasn't practical), you could generate a random index and map it to the valid values instead. This avoids creating a huge list, though it's overkill for your specific use case:

import random

def generate_custom_random_large():
    # Total valid numbers: 9 (1-9) + 5 (15-19) = 14 total
    random_pos = random.randint(0, 13)
    # Map position to valid number: first 9 positions = 1-9, rest = 15-19
    return random_pos + 1 if random_pos < 9 else 15 + (random_pos - 9)

For your needs, the first method is far easier to read and maintain.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:13:49