user

How to pick a random integer in a range in Python ?

alphonsio

To pick a random integer within a specific range in Python, you can use the `random`

module, which provides several functions to generate random numbers. The most commonly used functions for picking a random integer within a range are `randint()`

and `randrange()`

.

Here’s how you can use them:

**Using randint()**

The `randint(a, b)`

function returns a random integer N such that `a <= N <= b`

, `a`

and `b`

are inclusive.

```
import random
# Example: Pick a random integer between 1 and 10 (inclusive)
random_integer = random.randint(1, 10)
print(random_integer)
```

**Using randrange()**

The `randrange(start, stop[, step])`

function returns a randomly selected element from `range(start, stop, step)`

. The `start`

parameter is inclusive, and the `stop`

parameter is exclusive.

```
import random
# Example: Pick a random integer between 1 and 10 (inclusive)
random_integer = random.randrange(1, 11) # Note: 11 is exclusive
print(random_integer)
```

Both methods will give you a random integer in the specified range. If you need values within a closed range `[a, b]`

, prefer `randint()`

, but for more flexibility with ranges and steps, use `randrange()`

.