我想创建一个" football ";在python上的游戏,如果用户想要传球,我的代码应该有50%的概率有一个不完整的传球或完成在3和15码之间
我知道要打印码数,代码看起来像
import random
input("Enter r to run and p to pass")
p = print(random.randint(3,15))
但我不知道如何使"不完整";显示为50%的概率
您可以使用下面的代码。正如您已经定义了一个语句来选择3-15之间的随机数一样,您可以创建另一个语句来选择0或1(不保证%50)。同样在您的代码中,您将打印函数的返回值分配给参数。这绝对是错误的!Print
函数不返回任何值,因此将其赋值给另一个变量是没有意义的。
x = random.randint(0,1)
if x == 1:
random.randint(3,15)
else:
# incomplete pass
你可以这样写。
import random
inp = input("Enter r to run and p to pass")
if(inp == "p"):
print(random.choice([random.randint(3,15),0]))
elif(inp == "r"):
print("ran successfully")
This:random.choice([random.randint(3,15),0])
是重要位。random.choice
在一个列表中取多个值(本例中为2),并随机选择一个(2值=>50%概率)。
我还固定了输入输出的东西。要从用户那里获得输入,您可以将输入的值分配给如下变量:example = input("Your input here: ")
。如果您运行这行代码,并以potato
为例回答,您将能够打印example并获得potato(或用户回答的任何内容)。
如果你真的想充实你的游戏,我建议你看看模板字符串。它们可以让你做像这样的奇妙的事情:
import random
inp = input("Enter r to run and p to pass")
if(inp == "p"):
print(random.choice([f"Successfully passed the ball {random.randint(3,15)} yards","You tripped, the ball wasn't passed."]))
elif(inp == "r"):
print("Ran successfully.")