Example of Python random number usage

  • 2020-05-30 20:29:32
  • OfStack

This article illustrates the use of Python random Numbers as an example. I will share it with you for your reference as follows:

1. random.seed(int)

Give a random number object a seed value to generate a random sequence.

For the input of the same seed value, the random number sequence generated after the same.

The seed value is usually the change value such as the number of seconds of time, which is different from the random series produced in each run

seed() omits parameters, meaning that random Numbers are generated using the current system time


random.seed(10)
print random.random()  #0.57140259469
random.seed(10)
print random.random()  #0.57140259469  with 1 The random number generated is the same 
print random.random()  #0.428889054675
random.seed()      # Omitting parameters means taking the current system time 
print random.random()
random.seed()
print random.random()

2. random.randint(a,b)

Returns a random integer in the specified range, including the upper and lower bounds


print random.randint(1,10)

3. random.uniform(u,sigma)

Random normal floating point number


print random.uniform(1,5)

4. random.randrange(start,stop,step)

Take 1 random number in the range of upper and lower bounds according to the step size


print random.randrange(20,100,5)

5. random.random()

Random floating point number


print random.random()

6. Randomly select characters

Randomly select n characters


print random.sample('abcdefghijk',3)

Pick 1 character at random


print random.choice('abcde./;[fgja13ds2d')

Randomly select a few characters and concatenate them into a new string


print string.join(random.sample('abcdefhjk',4)).replace(" ","")

7.random.shuffle

Shuffle the list list at random

shuffle only applies to list, there might be an error such as' Str abcdfed ', and [' 1 ', '2', '3', '5', '6', '7']


item=[1,2,3,4,5,6,7]
print item
random.shuffle(item)
print item
item2=['1','2','3','5','6','7']
print item2
random.shuffle(item2)
print item2

PS: here are two more related online tools for your reference:

Online random number/string generation tool:
http://tools.ofstack.com/aideddesign/suijishu

High strength password generator:
http://tools.ofstack.com/password/CreateStrongPassword

For more information about Python, please check out the topics on this site: Python data structure and algorithm tutorial, Python Socket programming skills summary, Python function skills summary, Python string manipulation skills summary, Python introduction and advanced classic tutorial and Python file and directory manipulation skills summary.

I hope this article is helpful to you Python programming.


Related articles: