Python中带参数生成指定范围随机数的实现方法
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 inrange()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

