52

I've read the manual for pseudo-randomness in Python, and to my knowledge, you can only generate numbers up to a given maximum value, i.e. 0-1, 0-30, 0-1000, etc. I want to:

  • a) Generate a number between two ints, i.e. 5-55, and
  • b) Only include multiples of 5 (or those ending in 5 or 0, if that's easier)

I've looked around, and I can't find anywhere that explains this.

Has QUIT--Anony-Mousse
  • 76,138
  • 12
  • 138
  • 194
tkbx
  • 15,602
  • 32
  • 87
  • 122
  • 1
    Did you read http://docs.python.org/library/random.html? Scan down to the part titled "Functions for integers". – mtrw Nov 27 '11 at 17:04

4 Answers4

125

Create an integer random between e.g. 1-11 and multiply it by 5. Simple math.

import random
for x in range(20):
  print random.randint(1,11)*5,
print

produces e.g.

5 40 50 55 5 15 40 45 15 20 25 40 15 50 25 40 20 15 50 10
Has QUIT--Anony-Mousse
  • 76,138
  • 12
  • 138
  • 194
  • float: http://stackoverflow.com/questions/6088077/how-to-get-a-random-number-between-a-float-range-python – n611x007 Jun 13 '13 at 14:50
67
>>> import random
>>> random.randrange(5,60,5)

should work in any Python >= 2.

mtrw
  • 34,200
  • 7
  • 63
  • 71
  • 8
    While I feel this is the better answer, I would like to point out that this answer excludes 60 from being returned, which can be counterintuitive. I recommend using `random.randrage(5,55+1,5)` as a more clear way of doing this. – Hawkwing Aug 15 '13 at 17:07
13

If you don't want to do it all by yourself, you can use the random.randrange function.

For example import random; print random.randrange(10, 25, 5) prints a number that is between 10 and 25 (10 included, 25 excluded) and is a multiple of 5. So it would print 10, 15, or 20.

Felix Loether
  • 6,010
  • 2
  • 32
  • 23
6

The simplest way is to generate a random nuber between 0-1 then strech it by multiplying, and shifting it.
So yo would multiply by (x-y) so the result is in the range of 0 to x-y,
Then add x and you get the random number between x and y.

To get a five multiplier use rounding. If this is unclear let me know and I'll add code snippets.

Ofir Farchy
  • 7,657
  • 7
  • 38
  • 58