Python random randint() method

Python random 模块Python random module

Python random.randint()The method returns an integer within the specified range.

randint(start, stop)Equivalent torandrange(start, stop+1)。

Syntax

random.randint()The method syntax is as follows:

random.randint(start, stop)

Parameter description:

  • start-- Required, an integer, specifies the start value (inclusive), i.e., the generated random integer can take this value.
  • stop-- Required, an integer, specifies the end value (inclusive), i.e., the generated random integer can take this value.

Return value

Returns an integer within the specified range.

Example

The following example returns a number between 1 and 10 (greater than or equal to 1, less than or equal to 10):

Example

# Import the random package
import random

# Generate a random integer between 1 and 10
random_number = random.randint(1, 10)
print(random_number)

Output result:

8

In the above example,random.randint(1, 10)will generate a random integer between 1 and 10 (including 1 and 10), and assign it to the variable random_number.

Each time you run this code, you will get a different random integer.

Notes:

  • Ifa > b, it will raiseValueError, because the upper bound must be greater than or equal to the lower bound.
  • aandbIt can be any integer, including negative numbers.
  • random.randint()The method israndompart of the module, you need to first import therandommodule before using it.

Python random 模块Python random module

Other extensions