Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Python Random Number in a Range: Step-by-Step Guide

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

To get a random integer within a range in Python, use random.randint(a, b), which returns a whole number from a to b inclusive. For a random floating-point number, use random.uniform(a, b). Both are in the built-in random module, so no installation is needed. The exact function you pick depends on whether you want integers, floats, or a value from a custom set.

What You'll Need

  • Python 3 installed on your computer (any recent version works; the random module is part of the standard library).
  • A way to run Python code: the interactive interpreter, a script file, or an IDE such as IDLE, VS Code, or PyCharm.
  • Basic familiarity with importing modules and calling functions.

Step-by-Step

  1. Import the random module. At the top of your script or in the interpreter, type import random. This gives you access to all the random-number functions. You only need to do this once per script.
  2. Choose the right function for your data type. For whole numbers, use random.randint(start, end). For decimal numbers, use random.uniform(start, end). For a number from a range with a step (like even numbers only), use random.randrange(start, stop, step). Each has slightly different behavior at the boundaries, explained below.
  3. Call the function with your range. For example, random.randint(1, 10) returns an integer from 1 through 10, both ends included. random.uniform(0, 1) returns a float between 0 and 1. random.randrange(0, 10, 2) returns 0, 2, 4, 6, or 8 (the stop value is excluded). Assign the result to a variable if you need to use it later: number = random.randint(1, 100).
  4. Print or use the result. Run your script or type the call in the interpreter to see the output. If you are building a game or simulation, pass the variable into your logic instead of printing it.
  5. Seed the generator if you need reproducible results. By default, Python seeds the random generator from the system clock, so each run gives different numbers. If you want the same sequence every time (for testing or debugging), call random.seed(42) before generating numbers. Use any integer you like; the same seed always produces the same sequence.
  6. Test edge cases. Try calling your function with the smallest and largest values you expect, and with a range where start equals end. For randint(5, 5), you always get 5. For randrange(5, 5), you get an error because the range is empty. Knowing these behaviors prevents surprises.

Common Mistakes

  • Assuming randint excludes the upper bound. Unlike range() and randrange(), randint(a, b) includes both a and b. If you want to exclude b, use randrange(a, b) or randint(a, b-1).
  • Passing floats to randint. randint(1.0, 10.0) raises a ValueError because it expects integers. Use uniform for floats, or convert your bounds to integers first.
  • Forgetting to import random. A NameError: name 'random' is not defined means you skipped import random.
  • Using the wrong order of arguments. randint(10, 1) raises a ValueError because the start must be less than or equal to the end. Always put the smaller number first.
  • Expecting uniform to include the upper bound. random.uniform(a, b) may or may not include b due to floating-point rounding, but the probability of hitting exactly b is essentially zero. If you need a guaranteed inclusive float, handle it separately.
  • Using the random module for security. The random module is not cryptographically secure. For passwords, tokens, or security-sensitive values, use the secrets module instead.

Tips

  • Use random.choice(sequence) to pick a random item from a list, tuple, or string. For example, random.choice(['red', 'green', 'blue']).
  • To get multiple unique random numbers from a range, use random.sample(range(1, 50), 5). This returns a list of 5 distinct numbers.
  • If you need to shuffle a list in place, use random.shuffle(my_list). It modifies the original list and returns None.
  • For reproducibility in data science or testing, set the seed once at the start of your script. Note that the seed affects all subsequent random calls in that session.
  • When generating random floats, remember that uniform can return values very close to the bounds but rarely exactly on them. If your logic depends on exact boundary values, add explicit checks.
  • Use random.randrange(start, stop, step) when you need a number from an arithmetic progression, such as multiples of 5 between 0 and 100.

Troubleshooting

If you get a ValueError: empty range for randrange(), it means your start value is greater than or equal to the stop value when using randrange. Double-check that the first argument is smaller. For randint, a ValueError with a similar message means the start is greater than the end.

If you see TypeError: 'float' object cannot be interpreted as an integer, you passed a float to a function that expects integers, such as randint or randrange. Convert your bounds with int() or switch to uniform.

If your random numbers seem to repeat or follow a pattern, check whether you accidentally called random.seed() with the same value each time, or whether you are re-seeding inside a loop. Seeding should happen only once.

If you get the same number every time you run your script, you might have set a fixed seed and forgotten to remove it. Remove or comment out the random.seed() line to restore true randomness.

If you need a random number but your program crashes with NameError, confirm that import random is at the top of the file and that you are not shadowing the module name with a variable called random.

Frequently Asked Questions

How do I get a random integer between 1 and 10 in Python?

Use random.randint(1, 10). It returns an integer from 1 to 10, inclusive.

What is the difference between randint and randrange?

randint(a, b) includes both endpoints. randrange(start, stop, step) includes start but excludes stop, and allows a step value.

Can I generate a random float with a specific number of decimal places?

Yes. Generate a float with random.uniform(a, b), then round it with round(value, n) where n is the number of decimal places.

How do I make random numbers reproducible?

Call random.seed(some_integer) before generating numbers. The same seed produces the same sequence every time.

Is the random module suitable for passwords?

No. Use the secrets module for cryptographic security. The random module is designed for modeling and simulation, not security.

What happens if I use randint with the same start and end value?

It returns that value every time. For example, random.randint(7, 7) always returns 7.