我有一个问题,我必须从伪代码转换为 Python,并且出现错误:
Traceback (most recent call last):
File "C:/Users/Toshiba/Documents/Stevens stuff/Rings work.py", line 16, in <module>
Rings[i] = int(input(("How many teeth are on ring #i ?") % (i + 1)))
TypeError: not all arguments converted during string formatting
我的代码目前如下所示:
Rings = [0,0,0,0,0,0,0,0]
n = 0
while n == 0:
NumberofRings = int(input("How many rings are on your bike? "))
if NumberofRings <1 or NumberofRings >8:
print("Enter a number between 1 and 8")
else:
n = n + 1
Rings[0] = int(input("How many teeth are on ring 1? "))
for i in range (1, NumberofRings):
T = 0
while T == 0:
Rings[i] = int(input(("How many teeth are on ring #i ?") % (i + 1)))
if Rings[1] >= Rings(i - 1):
print("The number of teeth must be lower that the previious ring")
else:
T = 1
print ("=================")
for i in range(0, (len(Rings))):
print (("Ring #i has #i teeth") % (i + 1, Rings[i]))
最佳答案
此表达式使用 %
执行 string formatting :
("How many teeth are on ring #i ?") % (i + 1)
它告诉 Python 用 (i + 1)
代替地标(例如 %s
或 %d
)
在字符串“环#i 上有多少颗 dentry ?”
。但字符串中没有地标。
因此,Python 提示,
TypeError: not all arguments converted during string formatting
要修复错误,您可能需要
("How many teeth are on ring %d ?") % (i + 1)
当您需要对象的 str
表示形式时,使用 %s
。使用了%d
当您想要要求格式化的对象是 int 时。
您将在此行遇到相同的错误
print (("Ring #i has #i teeth") % (i + 1, Rings[i]))
您可以类似地修复它。
<小时/>另外,
if Rings[1] >= Rings(i - 1):
会引发错误
TypeError: 'list' object is not callable
因为括号用于调用函数,而方括号([
和 ]
)用于对容器对象中的项目进行索引。因此,Rings(i - 1)
应为 Rings[i-1]
。
如果我正确理解代码的用途,使用它也可能会更好
if Rings[i] >= Rings[i - 1]:
(注意 Rings[i]
而不是 Rings[1]
),因为 Rings[1]
使代码陷入无限循环如果 NumberofRings
大于 2。
关于字符串格式化代码中的 Python TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29878032/