How to have a percentage chance of executing a command

I have 10 things that I want to print if selected. However, each of them should have a different percentage chance.

I've tried 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, say chance <25, if randint is 10, wouldn't both odds <25 and probability <20 work at the same time?

Here is the code that I want to get after this happened.

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

EDIT:

Ok 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!")

+3

source to share

You code is correct. To solve this, you first need to add =

one as such:

if chance <= 20

The next thing to do is add a return statement at the end of your footprint, as such:

if (chance <= 20):
print(#Stuff)
return

This status return

Finally, the last thing to do is add all the other increments as such:

if (chance <= 20):
print(#Stuff)
return
if (chance <= 25):
print(#Stuff)
return

...

if (chance <= #last_number):
print(#Stuff)
return

It would be prudent to be sure that you stumble upon everything as stated in the odds you are looking for as well.

Good luck.

+1

source

ok, so if you want two mutually exclusive events, with one being 20% ​​of the time and the other 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 need to create 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"

+8

source

All Articles