30
votes

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?

4

4 Answers

48
votes

You could use random.random:

import random

if random.random() < percentage_chance:
    print('aaa')
13
votes
import random
if random.randint(0,100) < 36:
    do_stuff()
1
votes

Just to make it more explicitly clear and more readable:

def probably(chance):
    return random.random() < chance

if probably(35 / 100):
    do_the_thing()
-1
votes

This code returns a 1, 36% of the time

import random
import math
chance = 0.36
math.floor( random.uniform(0, 1/(1-chance)) )