我正在为学校编写一个 python 测验/计算器,但我在为测验创建随机问题时遇到了问题。
目前,我的代码如下:
while True:
if i + n == 10:
answer = input("If I have",i,"blue marbles and",n,"yellow marbles in a bag, what percentage of blue marbles are there? ")
else:
i = random.randint(1, 10)
n = random.randint(1, 10)
然而 python 出现错误:
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
TypeError: input expected at most 1 arguments, got 5
我尝试了多种解决方法,例如:
while True:
question = "If I have",i,"blue marbles and",n,"yellow marbles in a bag, what percentage of blue marbles are there? "
answer = input(question)
然而,当打印在 Shell 上时,它会打印“如果我有,4 [例如],'蓝色弹珠和',6,'袋子里的黄色弹珠,蓝色弹珠的百分比是多少?”。
如您所见,它打印引号和逗号,但正确包含变量 i 和 n。我看过 .strip() 函数,但所有教程都太困惑了,但我认为这就是我需要的!
任何人都可以使这行代码工作,它只是将问题打印为输入语句,同时包含变量吗?
请您参考如下方法:
input() 只接受一个一个参数,但你传入了 5 个:
input(
"If I have",
i,
"blue marbles and",
n,
"yellow marbles in a bag, what percentage of blue marbles are there? ")
首先将它们连接成一个字符串:
input("If I have {} blue marbles and {} yellow marbles in a bag, "
"what percentage of blue marbles are there? ".format(i, n))
这使用了 str.format() method将 i 和 n 的值插入到更大的字符串中。
您可能对此处的 print() 感到困惑,它显式地接受任意数量的参数并将每个参数转换为字符串,然后将它们写出到标准输出,每个参数用空格分隔。 input() 不提供此功能。
