Random module and pythonrandom Module

Source: Internet
Author: User

Random module and pythonrandom Module

The random module in Python is used to generate random numbers. Common functions are used as follows:

Random. randint

Function prototype: random. randint (a, B), which generates a randomIntegerN, where a <= n <= B

Random. uniform

Function prototype: random. uniform (a, B), which generates a randomFloating Point NumberN, where a <= n <= B

Random. random

Function prototype: random. random (), which generates a random value between 0 and 1.Floating Point NumberN, where 0 <= n <1

Random. choice

Function prototype: random. choice (sequence). Obtain a random element from the sequence (list, tuple, string ...).

Example: random string Extraction

>>> Import random
>>> Random. choice (["apple", "orange", "egg"])
'Egg'

 

Random. randrange

Function prototype: random. randrange ([start], stop [, step]), which obtains a random number from the set in which the specified base number increments.

For example, an even number between 0 and 100 is randomly obtained.

>>> Import random
>>> Random. randrange (0,101, 2)
38

 

Random. sample

Function prototype: random. sample (sequence, k), which randomly retrieves fragments of the specified length from the specified sequence

Example: select a specific number of characters in the string, and randomly obtain four elements in the list as a part.

>>> Import random
>>> Random. sample ("goodboy", 2)
['D', 'O']
>>> Random. sample (["I", "love", 3, "python", 66], 4)
['Python', 'love', 'I', 3]

 

Random. shuffle

Function prototype: random. shuffle (x [, random ]).

Example: shuffling

>>> Import random
>>> Cards = [1, 2, 3, 4, 5, 6]
>>> Random. shuffle (cards)
>>> Cards
[3, 5, 2, 4, 6, 1]

 

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.