乐闻世界logo
搜索文章和话题

What method can be used to generate random numbers in Python?

1个答案

1

In Python, generating random numbers primarily relies on the random module. Here are several commonly used methods:

  1. random():

    • The random.random() method returns a random floating-point number between 0 and 1, inclusive of 0 but exclusive of 1.
    • For example:
      python
      import random num = random.random() print(num) # outputs something like 0.37444887175646646
  2. randint(a, b):

    • The random.randint(a, b) method returns a random integer within the specified range, inclusive of both boundaries a and b.
    • For example:
      python
      import random num = random.randint(1, 10) print(num) # outputs an integer between 1 and 10, inclusive of both 1 and 10
  3. randrange(start, stop[, step]):

    • The random.randrange(start, stop[, step]) method returns a random number within the specified range, allowing specification of a step.
    • For example:
      python
      import random num = random.randrange(0, 101, 5) print(num) # outputs a multiple of 5 between 0 and 100
  4. uniform(a, b):

    • The random.uniform(a, b) method returns a random floating-point number between a and b, inclusive of a but exclusive of b.
    • For example:
      python
      import random num = random.uniform(1.5, 4.5) print(num) # outputs a floating-point number between 1.5 and 4.5

Additionally, to achieve reproducible results, the random.seed() method can be used to set the seed value for the random number generator:

python
import random random.seed(10) # sets the seed value print(random.random()) # outputs the same result every time

These are several common methods for generating random numbers in Python.

2024年8月9日 09:57 回复

你的答案