Python random randint() Method
Python random.randint() The method returns an integer within a specified range.
randint(start, stop) is equivalent to randrange(start, stop+1)。
Syntax
The syntax of the random.randint() method is as follows:
random.randint(start, stop)
Parameter Description:
- start -- required, an integer specifying the start value (inclusive), that is, the generated random integer can take this value.
- stop -- required, an integer specifying the end value (inclusive), that is, 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
)
(
random_number
)
Output result:
8
In the above example, random.randint(1, 10) generates a random integer between 1 and 10 (including 1 and 10) and assigns it to the random_number variable.
Every time this code runs, a different random integer is produced.
Notes:
- If both the
a > b, then aValueErroris raised, because the upper bound must be greater than or equal to the lower bound. aandbcan be any integer, including negative numbers.random.randint()The method israndomis part of therandommodule, which must be imported before use.
Python random Module