-1

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 
i = 0
while i < 10:
   if z == True:
     print(True)
   else:
     print(False)
   i = i+1
Eran Moshe
  • 3,062
  • 2
  • 22
  • 41
luscgu00
  • 43
  • 6
  • 6
    Does this answer your question? [True or false output based on a probability](https://stackoverflow.com/questions/5886987/true-or-false-output-based-on-a-probability) – Lev Leontev Oct 24 '22 at 09:07

2 Answers2

0

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)
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
0

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)
Eran Moshe
  • 3,062
  • 2
  • 22
  • 41