我有一个问题,我必须从伪代码转换为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]))
答案 0 :(得分:2)
此表达式使用%
执行string formatting:
("How many teeth are on ring #i ?") % (i + 1)
它告诉Python用(i + 1)
代替地标(例如%s
或%d
)
在字符串"How many teeth are on ring #i ?"
中。但是字符串中没有地标。
因此,Python抱怨,
TypeError: not all arguments converted during string formatting
要修复错误,您可能需要
("How many teeth are on ring %d ?") % (i + 1)
当您需要对象的%s
表示时,将使用 str
。使用%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]
大于2,NumberofRings
会在无限循环中捕获代码。