Tyler Seymour
Tyler Seymour

Reputation: 617

Randomness in Python

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?

Upvotes: 7

Views: 1396

Answers (2)

Óscar López
Óscar López

Reputation: 235984

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

Upvotes: 6

hd1
hd1

Reputation: 34657

if random.random() > 0.5: 
    # your app does this 
    pass
else: 
    # your app does that
    pass

Upvotes: 12

Related Questions