askvity

How do you create a random number between in Python?

Published in Python Random Number Generation 1 min read

You can create random numbers within a specific range in Python using the random module, which offers several functions for different purposes:

Generating Random Floating-Point Numbers

  • random.random(): This function returns a random floating-point number between 0.0 (inclusive) and 1.0 (exclusive).

    import random
    
    random_number = random.random()
    print(random_number) # Output: A random number between 0.0 and 1.0
  • random.uniform(a, b): This function returns a random floating-point number N such that a <= N <= b for a <= b and b <= N <= a for b < a. It includes both endpoints.

    import random
    
    random_number = random.uniform(1.0, 10.0)
    print(random_number) # Output: A random number between 1.0 and 10.0

Generating Random Integers

  • random.randint(a, b): This function returns a random integer N such that a <= N <= b. It includes both endpoints.

    import random
    
    random_integer = random.randint(1, 10)
    print(random_integer) # Output: A random integer between 1 and 10 (inclusive)

Summary Table

Function Returns Range (inclusive unless noted) Data Type Example
random.random() Random floating-point number 0.0 to 1.0 (exclusive of 1.0) float random.random()
random.uniform(a, b) Random floating-point number a to b float random.uniform(1.0, 10.0)
random.randint(a, b) Random integer a to b int random.randint(1, 10)

These functions provide flexible ways to generate random numbers within specific ranges in Python, depending on whether you need a floating-point number or an integer.

Related Articles