askvity

How do you set a random number range in Python?

Published in Python Random Numbers 1 min read

To set a random number range in Python, use the random module. You can generate random integers within a specified range using random.randint(a, b), and random floating-point numbers within a range using random.uniform(a, b).

Generating Random Integers

The random.randint(a, b) function returns a random integer N such that a <= N <= b. Both a and b are included in the possible values.

import random

# Generate a random integer between 1 and 10 (inclusive)
random_integer = random.randint(1, 10)
print(random_integer)

Generating Random Floating-Point Numbers

The random.uniform(a, b) function returns a random floating-point number N such that a <= N <= b.

import random

# Generate a random floating-point number between 1.0 and 5.0
random_float = random.uniform(1.0, 5.0)
print(random_float)

Other Useful Functions

  • random.random(): Returns a random floating-point number between 0.0 (inclusive) and 1.0 (exclusive). You can then scale and shift this value to fit your desired range.

    import random
    
    # Generate a random float between 5 and 10
    random_scaled = 5 + random.random() * 5 # (10-5 = 5)
    print(random_scaled)

Example: Creating a Function for a Custom Range

You can create a function to encapsulate the logic for generating a random number within a specific range:

import random

def generate_random_number(min_value, max_value, is_integer=True):
  """Generates a random number within the specified range.

  Args:
    min_value: The minimum value of the range (inclusive).
    max_value: The maximum value of the range (inclusive).
    is_integer:  A boolean indicating whether to return an integer or a float.  Defaults to True (integer).

  Returns:
    A random number within the range.
  """
  if is_integer:
    return random.randint(min_value, max_value)
  else:
    return random.uniform(min_value, max_value)


# Example Usage:
random_int = generate_random_number(1, 100)
print(f"Random Integer: {random_int}")

random_float = generate_random_number(0.0, 1.0, is_integer=False)
print(f"Random Float: {random_float}")

In summary, random.randint() is ideal for integers, while random.uniform() is suitable for floating-point numbers. You can combine random.random() with scaling and shifting for alternative floating-point range generation.

Related Articles