Randomness in Python

I use random.random() to get a random float (obviously!). But I really want to do something like:

 there a 30% chance my app does this: pass else: pass 

Can you guys help me structure this?

+6
source share
2 answers
 if random.random() > 0.5: # your app does this pass else: # your app does that pass 
+11
source

Try the following:

 if random.randint(1, 10) in (1, 2, 3): print '30% chance' else: print '70% chance' 

Here randint will generate a number from 1 to 10, there is a 30% chance that it will be between 1-3 and 70% chance that it will be between 4-10

+6
source

All Articles