How to generate random float?

QuestionsQuestions8 SkillsProPython Control StructuresNov, 23 2025
0132

To generate a random float in Python, you can use the random.uniform() function from the random module. This function allows you to specify a range, and it will return a random floating-point number within that range.

Syntax

random.uniform(a, b)
  • a: The lower bound of the range (inclusive).
  • b: The upper bound of the range (inclusive).

Example Usage

Here’s a simple example demonstrating how to use random.uniform() to generate a random float:

import random

# Generate a random float between 10 and 100
random_float = random.uniform(10, 100)

print(f"The random float generated is: {random_float}")

Explanation

  1. Import the Module: First, you need to import the random module.
  2. Call random.uniform(a, b): Replace a and b with the desired range values. The function will return a random float between a and b.
  3. Print the Result: You can print or use the generated random float as needed.

Example in a Context

Here’s how you might use random.uniform() in a scenario where you need a random float for a calculation:

import random

# Generate a random float between 1.0 and 10.0
random_float = random.uniform(1.0, 10.0)

# Use the random float in a calculation
result = random_float * 2
print(f"The random float is: {random_float}")
print(f"The result of the calculation is: {result}")

In this example, a random float between 1.0 and 10.0 is generated, and then it is used in a simple calculation.

0 Comments

no data
Be the first to share your comment!