ODP ODP - 1 year ago 68
Python Question

How to print a random number from a set, except from one or two of the numbers?

I want to print a random number from 1 to 10, but I do not want to include 3 or 4.

I know that I need

print randint(1,11)

to print a random number, but how do I make sure that 3 or 4 are not generated?

Answer Source

One of many ways is using random.choice(), which returns a random element from the non-empty sequence:

>>> import random
>>> a = range(1,11)
>>> a.remove(3)
>>> a.remove(4)
>>> a
[1, 2, 5, 6, 7, 8, 9, 10]
>>> random.choice(a)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download