Sling Academy
Home/Python/Python: Generate a Random Integer between Min and Max

Python: Generate a Random Integer between Min and Max

Last updated: June 03, 2023

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!

Next Article: Python: Generate a Random Float between Min and Max (3 ways)

Previous Article: Python: Get Numeric Value from User Input

Series: Python – Numbers & Math Tutorials

Python

You May Also Like

  • Python Warning: Secure coding is not enabled for restorable state
  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types