1

I am using a number generator currently using the code below

from random import randint
print(randint(0,1))

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%) probability

how can i achieve this effectively in python ?

user3842234
  • 77
  • 1
  • 9

1 Answers1

5

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!')
Uriel
  • 15,579
  • 6
  • 25
  • 46
  • Practically speaking, the short version could be `print(random() < 0.8)`. – TigerhawkT3 Nov 26 '16 at 21:39
  • @Fredrik his comment is good. he suggest that if he want to use a variable determined that way for determining action, he may use this shorter version to create a boolean variable – Uriel Nov 26 '16 at 22:09
  • That's why I said "practically speaking." The only noticeable difference between `1`/`0` and `True`/`False` is how they appear when printed, and it's unlikely that the user is supposed be shown this result. It's much more likely to be used later in the program, in which case integers and booleans are pretty much interchangeable. – TigerhawkT3 Nov 26 '16 at 22:09