Random in python generates random numbers

random.random()

Used to generate a 0 to 1, random floating point number: 0<= n <1.0

import random
print(random.random()) # 0.967675107001813

random.uniform(a, b)

Used to generate floating point numbers between [a,b]. If a> b, the generated random number n: b <= n <= a. If a <b, then a <= n <= b.

import random
print(random.uniform(1,10)) # 4.680684777712934

random.randint(a, b)

Used to generate an integer in the specified range. Among them, the parameter a is the lower limit, and the parameter b is the upper limit. The generated random number n: a <= n <= b

import random
print(random.randint(1,10)) # 2

Note : random() is not directly accessible, you need to import the random module


Other methods of random module:

  • random.choice()
    can select a random element from any sequence, such as a list, and return it, which can be used for strings, lists, tuples, etc.
import random
a = [1,2,3,4,5,6]
print(random.choice(a)) # 3
  • random.sample(sequence, k)
    randomly obtain fragments of the specified length from the specified sequence and arrange them randomly . Note: The sample function does not modify the original sequence.
import random
a = [1,2,3,4,5]
b = random.sample(a,3)
print(b) # [5, 2, 1]
print(a) # [1, 2, 3, 4, 5]

Guess you like

Origin blog.csdn.net/weixin_43974265/article/details/104951991