How to have a percentage chance of a command to run

Yami picture Yami · Sep 26, 2014 · Viewed 12k times · Source

I have 10 things that I want to be printed if they are picked. However each should have a different percentage chance of happening though.

I tried doing the following:

    chance = (random.randint(1,100))
    if chance < 20:
        print ("20% chance of getting this")

The problem is that if I do another one with say, chance <25, if the randint is 10, wouldn't both the chance <25 and chance <20 both run at the same time?

Here is the code I want to have the chance stuff going on after.

print ("You selected Grand Theft Auto")
gta = input ("To commit GTA input GTA")
if gta in ("gta", "Gta", "GTA"):

EDIT:

Alright so I tried this but it keeps giving 3 outputs.

print ("You selected Grand Thief Auto")
    gta = input ("To commit GTA type GTA")
    if gta in ("gta", "Gta", "GTA"):
        chance = random.randint(0,100)
        if chance <= 1:
            print ("You stole a Bugatti Veryron")
        chance = random.randint(0,100)
        if chance <= 5:
            print ("You stole a Ferrari Spider")
        chance = random.randint(0,100)
        if chance <= 10:
            print ("You stole a Audi Q7")
        chance = random.randint(0,100)
        if chance <= 15:
            print ("You stole a BMW X6")
        chance = random.randint(0,100)
        if chance <= 20:
            print ("You stole a Jaguar X Type")
        chance = random.randint(0,100)
        if chance <= 25:
            print ("You stole a Ford Mondeo")
        chance = random.randint(0,100)
        if chance <= 30:
            print ("You stole a Audi A3")
        chance = random.randint(0,100)
        if chance <= 35:
            print ("You stole a Ford Fiesta")
        chance = random.randint(0,100)
        if chance <= 40:
            print ("You stole a Skoda Octavia")
        chance = random.randint(0,100)
        if chance <= 45:
            print ("You got caught!")

Answer

Gregory Nisbet picture Gregory Nisbet · Sep 26, 2014

okay so if you want two mutually exclusive events with one occurring 20% of the time and the other occurring 25% of the time, then

chance = random.randint(1,100)
if chance <= 20:
    print "20% chance of getting this"
elif chance <= 20+25:
    print "25% change of getting this"

if you want them to be independent and not influence each other, you have to generate another random number.

chance = random.randint(1,100)
if chance <= 20:
    print "20% chance of getting this"

chance = random.randint(1,100)
if chance <= 25:
    print "25% change of getting this"