Back to Python
2026-05-046 min read

random.uniform(a, b) (Python Programming)

Learn random.uniform(a, b) (Python Programming) step by step with clear examples and exercises.

Why This Matters

Python's random.uniform(a, b) function is an essential tool for generating random floating-point numbers within a specified range. Its versatility makes it indispensable in various applications such as simulations, game development, statistical analysis, and more. By mastering this function, you will be well-prepared to tackle complex problems efficiently.

Prerequisites

To fully understand the random.uniform(a, b) function, it is crucial that you have a good grasp of the following concepts:

  1. Basic Python syntax and data types
  2. Control structures like if, for, and while loops
  3. Functions and their usage in Python
  4. The Python Standard Library's random module
  5. Understanding of floating-point numbers and their properties
  6. Familiarity with the concept of a seed value in random number generation
  7. Knowledge of how to handle exceptions and errors in Python

Core Concept

The random.uniform(a, b) function generates a random floating-point number n such that a <= n < b. Here's an example:

import random
print(random.uniform(0, 10))

Executing this code will output a random float between 0 and 10 (inclusive for 0 and exclusive for 10). The random module is part of Python's Standard Library, so you don't need to install anything extra to use it.

Understanding the Seed

Python's random number generator uses a seed value to produce sequences of numbers. If you want to generate different sequences each time your program runs, you can change the seed by calling random.seed(number) before using any other functions from the random module.

import random
random.seed(42) # Set the seed to 42 for reproducible results
print(random.uniform(0, 10))
print(random.uniform(0, 10))

In this example, setting the seed ensures that the same sequence of random numbers is generated each time the program runs.

Seed Value Properties

  • The seed value can be any integer.
  • Changing the seed will result in a different sequence of random numbers.
  • If you don't set a seed explicitly, Python uses a different seed each time it starts, producing a different sequence of random numbers every time your program runs.

Handling Exceptions and Errors

When working with random number generation, it is essential to handle exceptions and errors properly. For example, if you try to generate a floating-point number outside the specified range (i.e., b < a), Python will raise a ValueError. To avoid this issue, always ensure that a is less than b.

import random
try:
print(random.uniform(-10, 1))
except ValueError as e:
print("Error:", e)

In this example, we're using a try-except block to handle the ValueError that would be raised if we tried to generate a number outside the specified range.

Worked Example

Let's create a simple simulation of rolling a weighted die with six faces: four 1s, one 2, and one 3. We'll use random.uniform(a, b) to simulate the roll and calculate the total score after rolling the die 100 times.

import random
total_score = 0
for _ in range(100):
roll = (random.uniform(1, 5) == 1) * 1 + (random.uniform(1, 2) == 1) * 2 + (random.uniform(2, 3) == 1) * 3
total_score += roll
print("Total Score:", total_score)

In this example, we're using multiple conditions to simulate the die roll and assign points accordingly. The output will vary each time you run the code due to the random number generation.

Common Mistakes

  1. Not importing the random module: Remember to include import random at the beginning of your script.
  2. Incorrect range for a or b: Make sure that a is less than b. If not, you'll get an error.
  3. Using the function without seeding: If you need reproducible results, set the seed before using random.uniform(a, b).
  4. Forgotten multiplication or addition: Ensure that you multiply or add the correct values when using multiple conditions in your roll simulation.
  5. Using random.uniform(a, a): This will always return the same value (a), as the minimum and maximum are the same. Be aware of this when writing conditional statements.
  6. Incorrectly handling floating-point rounding issues: If you need an integer result from your random number generation, use int(random.uniform(a, b)). However, be mindful that this may still produce values outside the specified range due to rounding issues.
  7. Not handling exceptions and errors properly: When working with random number generation, it is crucial to handle exceptions and errors appropriately to avoid unexpected behavior in your code.

Practice Questions

  1. Write a script to generate 50 random numbers between 1 and 100 and calculate their average.
  2. Modify the weighted die example to include a face with a 4 and another with a 5. Calculate the total score after rolling the die 100 times.
  3. Write a script that generates a random floating-point number between -100 and 100, then finds the closest integer to this number.
  4. Write a function that takes an integer n as input and returns the average of n random numbers generated by random.uniform(0, 1).
  5. Create a script that generates a sequence of 100 random floating-point numbers between 0 and 1 using different seed values (e.g., 1, 2, 3, ..., 100). Calculate the average for each sequence and compare their differences.
  6. Write a script to generate a random float between 0 and 1000, then round it to the nearest integer. If the rounded number is even, subtract 1; if it's odd, add 1. Repeat this process 100 times and calculate the final sum.
  7. Modify the weighted die example to include a face with a 6 that has a probability of 0.25. Calculate the total score after rolling the die 100 times.
  8. Write a script that generates a random float between 0 and 1, then finds the nearest multiple of 0.1. If the closest multiple is 0.1 or 0.9, multiply it by -1. Repeat this process 100 times and calculate the final sum.

FAQ

What is the default seed value for Python's random module?

Python uses a different seed each time it starts, so there's no default seed value. If you don't set a seed explicitly, you'll get a different sequence of random numbers every time your program runs.

Can I use random.uniform(a, b) to generate an integer within a specific range?

No, random.uniform(a, b) generates floating-point numbers. If you need an integer, you can use int(random.uniform(a, b)). However, this may still produce values outside the specified range due to rounding issues.

Is there a way to generate a specific sequence of random numbers using Python's random module?

While it's not possible to generate a specific sequence of random numbers, you can use the random.shuffle() function to rearrange a list in a seemingly random order or create a pseudo-random sequence using a seed value. Additionally, there are other libraries like numpy that offer more advanced random number generation capabilities.

What is the difference between random.uniform(a, b) and random.randrange(start, stop)?

random.uniform(a, b) generates a floating-point number within the specified range (inclusive for start and exclusive for end), while random.randrange(start, stop) generates an integer within the specified range (inclusive for both start and end).

random.uniform(a, b) (Python Programming) | Python | XQA Learn