I'm using random.random() to get a random float (obviously!). But what I really want to do is something like:
there's a 30% chance my app does this:
pass
else:
pass
Can you guys help me structure this?
if random.random() > 0.5:
# your app does this
pass
else:
# your app does that
pass
random() < x since x would directly correspond to the probability of the condition's being true.random.random() < .3, but of course .3 > random.random() means the exact same thing, as would the answer's random.random() > .7.Try this:
if random.randint(1, 10) in (1, 2, 3):
print '30% chance'
else:
print '70% chance'
Here randint will generate a number between 1-10, there's a 30% chance that it's between 1-3 and a 70% chance that it's between 4-10
== 1 if you wanted.if random.randrange(10) < 3 is just as reasonable as random.random() < .3; it's just a matter of which one seems clearer to you.
hd1's answer; if you're thinking of it as "3 out of 10", accept Óscar López's answer. They're both correct, and equivalent, it's just a matter of which is more readable or seems more "right" in your case.