如何运行命令的百分比

Yam*_*ami 5 python random percentage

如果他们被挑选,我有10件我想要打印的东西.但是每个人都应该有不同的发生几率.

我尝试过以下操作:

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

问题是,如果我再说一次,机会<25,如果randint是10,那么机会<25和机会<20都不会同时运行吗?

这是我想要有机会继续的代码.

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

编辑:

好吧所以我尝试了这个,但它一直提供3个输出.

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!")
Run Code Online (Sandbox Code Playgroud)

Gre*_*bet 9

好吧,如果你想要两个相互排斥的事件,其中一个发生在20%的时间,另一个发生在25%的时间,那么

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

如果你希望它们是独立的而不是相互影响,你必须生成另一个随机数.

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"
Run Code Online (Sandbox Code Playgroud)


T.W*_*ody 1

你的代码是正确的。解决这个问题的方法是首先在=第一个内部添加一个if-statement,如下所示:

 if chance <= 20
Run Code Online (Sandbox Code Playgroud)

接下来可以做的就是在打印末尾添加一个 return 语句,如下所示:

 if (chance <= 20):
      print(#Stuff)
      return
Run Code Online (Sandbox Code Playgroud)

return语句将完成程序正在执行的任何操作,并返回到另一个任务,或者只是完成。

最后,最后要做的事情是添加所有其他增量,如下所示:

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

 ...

 if (chance <= #last_number):
      print(#Stuff)
      return
Run Code Online (Sandbox Code Playgroud)

明智的做法是确保您所寻找的赔率所表明的一切都在增加。

祝你好运。