字符串格式代码中的Python TypeError

时间:2015-04-26 13:08:56

标签: python pseudocode

我有一个问题,我必须从伪代码转换为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]))

1 个答案:

答案 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会在无限循环中捕获代码。