user3842234 user3842234 - 1 year ago 70
Python Question

Random number generation with a x chance of it being 1

I am using a number generator currently using the code below

from random import randint

which while it works, i need to generate either 0 or 1 but i need the generator to generate
1 with a x (say 80%)

how can i achieve this effectively in python ?

Answer Source

random.random() will return a random decimal between 0 and 1. Use this value to determine your choice:

from random import random 
print(0 if random() > 0.8 else 1)

and of course, 0.8 can be replaced with any probability (60% -> 0.6).

As @TigerhawkT3 noted, you might use the shorter version random() < 0.8 to generate a boolean variable, if you want to do an action based on that random probability, like

x = random() < 0.8
if x:
    print('hello world!')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download