简单问题:
percentage_chance = 0.36
if some_function(percentage_chance):
# action here has 36% chance to execute
pass
我该如何编写some_function
,或者涉及percentage_chance
的表达式来解决这个问题?
random.random
:import random
if random.random() < percentage_chance:
print('aaa')
import random
if random.randint(0,100) < 36:
do_stuff()
randrange
函数。 - SilentGhostrandrange
会改变行为。 - Robin Andrews为了更明确易懂:
def probably(chance):
return random.random() < chance
if probably(35 / 100):
do_the_thing()
import random
import math
chance = 0.36
math.floor( random.uniform(0, 1/(1-chance)) )