Python Module---random module __python

Source: Internet
Author: User

The random module in Python is used to generate random numbers. Here are some of the most commonly used functions in the random module.
Random

Random.random () is used to generate a 0 to 1 number of random character points: 0 <= N < 1.0

>>> print random.random ()
0.283212844881
Uniform

Random.uniform is used to generate a number of random characters within a specified range, one of two parameters is the upper bound and one is the lower bound.

>>> print Random.uniform (1,10) #同random. Uniform (10,1)
1.2558047703
>>> Print Random.uniform (10,1)
6.78930988147
Randint

Random.randint () is used to generate an integer within a specified range. Where parameter A is the lower bound, parameter B is the upper limit and cannot be reversed.

#print Random.randint #该语句是错误的. The lower bound must be less than the upper limit. Randrange

Randrange ([start],stop[, step]) gets a random number from the specified range, in a collection that is incremented by the specified cardinality. such as: Random.randrange (10, 100, 2), the result is equivalent from [10, 12, 14, 16, ... 96,98] sequence to obtain a random number. Choice

Gets a random element from the sequence.

Print Random.choice ("Learning python")
print Random.choice (["Jgood", "is", "a", "handsome", "boy"])
print Random.cho Ice ("Tuple", "List", "Dict")

Shuffle

Shuffle (X[,random] is used to disrupt elements in a list.

>>> p = [' A ', ' B ', ' C ']
>>> random.shuffle (p)
>>> print P
[' A ', ' C ', ' B ']
Sample

Random.sample (sequence,k) that randomly obtains a fragment of the specified length from the specified sequence. The sample function does not modify the original sequence.

>>> print random.sample ([' A ', ' B ', ' C ', ' d '],3]
[' A ', ' B ', ' C ']

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.