Search code examples
pythonrandom

Percentage chance to make action


Simple problem:

percentage_chance = 0.36

if some_function(percentage_chance):
   # action here has 36% chance to execute
   pass

How can I write some_function, or an expression involving percentage_chance, in order to solve this problem?


Solution

  • You could use random.random:

    import random
    
    if random.random() < percentage_chance:
        print('aaa')