我有一个问题,我必须将伪代码转换为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
在字符串"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将代码陷入无限循环。

10-06 09:16