I have an if statement which should be executet to 80-%.
Easy example:
x = True # 80% of the time
y = False # 20% of the time
z = # Either x or y
while i < 10:
if z == True:
print(True)
else:
print(False)
i = i 1
CodePudding user response:
The choices
function from the random
module accepts weights for the possible outcomes. So you could just use:
for i in range(10):
print(random.choices((True, False), (80, 20))
or as choices
can return a number of values:
for i in random.choices((True, False), (80, 20), k=10):
print(i)
CodePudding user response:
You can use random.random()
to get a random number between 0 to 1 with a uniform distribution.
so you expect this number to be < 0.8 80% of the times and > 0.8 20% of the times.
import random
for i in range(10):
r = random.random()
if r < 0.8:
print(True)
else:
print(False)