Python's method of generating random Numbers

  • 2020-04-02 13:19:36
  • OfStack

If you don't understand the relationship between the most commonly used functions in Python to generate random Numbers and random modules, the following article is about the relationship between Python to generate random Numbers and the most commonly used functions in the random module.

Random. Random () is used for generation

Used to generate a random number of points in a specified range, with two arguments, one for the upper bound and one for the lower bound. If a > B, then generate a random number


n: a <= n <= b . if  a <b .   the  b <= n <= a . 

print random.uniform(10, 20) 
print random.uniform(20, 10) 
#---- 
#18.7356606526 
#12.5798298022 
random.randint 

Used to generate an integer in a specified range. Where a is the lower limit, b is the upper limit, and Python generates random Numbers


print random.randint(12, 20) # Generated random Numbers n: 12 <= n <= 20 
print random.randint(20, 20) # The result is always 20 
#print random.randint(20, 10) # This statement is incorrect.  

The lower limit must be less than the upper limit.

The random. Randrange

This article is part of an introduction to a python application that generates random Numbers from a collection that grows from the specified scope to the specified cardinality.

Random integer:
> > > Import the random
> > > The random randint (0 13)
21

Random even Numbers between 0 and 100:
> > > Import the random
> > > The random randrange (0, 101, 2)
42

Random floating point number:
> > > Import the random
> > > The random. The random ()
0.85415370477785668
> > > The random uniform (1, 10)
5.4221167969800881

Random characters:
> > > Import the random
> > > The random choice (' abcdefg & f # % ^ *)
'd'

Select a specific number of characters from multiple characters:
> > > Import the random
The random sample (' abcdefghij, 3)
[' a ', 'd', 'b']

Select a specific number of characters from multiple characters to form a new string:
> > > Import the random
> > > The import string
> > > String. The join (random sample ([' a ', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'I' and 'j'], 3)). R
Eplace (" ", "")
'fih

Randomly selected string:
> > > Import the random
> > > The random choice ([' apple ', 'pear', 'peach', 'orange', 'lemon'])
'lemon'

Shuffle:
> > > Import the random
> > > Items = [1, 2, 3, 4, 5, 6]
> > > The random shuffle (items)
> > > The items
[3, 2, 5, 6, 4, 1]

PS: finally, I will provide you with two online tools for your reference:

Online random number/string generation tool:
(link: http://tools.jb51.net/aideddesign/suijishu)

High-strength random character password generator:
(link: http://tools.jb51.net/password/CreateStrongPassword)


Related articles: