字符串格式中的Python TypeError

2024-10-01 17:27:54 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: 代码ininputifonaremanyhow
1条回答
网友
1楼 · 发布于 2024-10-01 17:27:54

此表达式使用%执行string formatting

("How many teeth are on ring #i ?") % (i + 1)

它告诉Python用(i + 1)代替placemarker(例如%s%d) 在字符串"How many teeth are on ring #i ?"中。但是字符串中没有placemarker。 因此,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]),因为如果NumberofRings大于2,则Rings[1]会将代码困在无限循环中。你知道吗

相关问题 更多 >

    热门问题