Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Randomness in Python

Tags:

python

random

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?

like image 546
Tyler Seymour Avatar asked Dec 08 '12 02:12

Tyler Seymour


2 Answers

if random.random() > 0.5: 
    # your app does this 
    pass
else: 
    # your app does that
    pass
like image 51
hd1 Avatar answered Oct 06 '22 00:10

hd1


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

like image 31
Óscar López Avatar answered Oct 05 '22 23:10

Óscar López