To generate a random integer between two given integers, the quickest and most convenient way is to use the randint()
function from the random
module. The minimum and maximum values are both included (that means one of them has a chance to be the result you get).
Syntax:
result = random.randint(min, max)
For more clarity, see the example below.
Example:
import random
# Generate a random integer between 0 and 100
print(random.randint(0, 100))
# Generate a random integer between -100 and 100
print(random.randint(-100, 100))
# Generate a random integer between 200 and 500
print(random.randint(200, 500))
Output (the output will change each time you execute the code because of the randomness):
24
17
237
Alternatives
In general, it’s often possible that you can find more than one way to solve a problem in Python. Besides the technique mentioned above, you can also create a random integer between min and max like this:
result = random.randrange(min, max + 1)
Or:
result = random.choice(range(min, max + 1))
Both min and max have a chance as a result, no upper or lower bounds are excluded.
Example:
import random
# comment out this line if you want to get different results
# each time you run the code
random.seed(1)
# min = 1, max = 9
x = random.randrange(1, 10)
print(x)
# min = 10, max = 20
y = random.choice(range(10, 21))
print(y)
Output:
3
19
Hope this helps. Happy coding!