如果拣选了我想打印的10样东西。但是,每个人都有不同的发生百分比机会。
我尝试执行以下操作:
chance = (random.randint(1,100))
if chance < 20:
print ("20% chance of getting this")
问题是,如果我再说一次机会
这是我想让事情继续进行的代码。
print ("You selected Grand Theft Auto")
gta = input ("To commit GTA input GTA")
if gta in ("gta", "Gta", "GTA"):
编辑:
好吧,所以我尝试了这个,但它始终提供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!")
最佳答案
您的代码是正确的。解决此问题的方法是,首先在第一个=
内添加一个if-statement
,如下所示:
if chance <= 20
下一步可以做的是在打印的末尾添加return语句,如下所示:
if (chance <= 20):
print(#Stuff)
return
该
return
语句将完成程序正在执行的所有操作,并返回到另一个任务,或者只是完成。最后,要做的最后一件事是添加所有其他增量,如下所示:
if (chance <= 20):
print(#Stuff)
return
if (chance <= 25):
print(#Stuff)
return
...
if (chance <= #last_number):
print(#Stuff)
return
确保您按照期望的几率将所有事情都提高了也是明智的。
祝你好运。
关于python - 如何有一定百分比的机会运行命令,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26049942/