英文:
not all arguments converted during string formatting (while passing arguments to function)
问题
I am getting error "not all arguments converted during string formatting" while running this code please explain how to fix this and what is this error
def multiples(l, n):
count = 0
for i in l:
if (i % n == 0):
count += 1
return count
m = input("no of elements: ")
l = []
print("enter elements:")
for i in range(int(m)):
l.append(input())
n = int(input("enter no to find no.of multiples: "))
print(multiples(l, n))
error:
Exception has occurred: TypeError
not all arguments converted during string formatting
line 4, in multiples
if (i % n == 0):
line 13, in <module>
print(multiples(l, n))
TypeError: not all arguments converted during string formatting
错误信息:"not all arguments converted during string formatting",请解释如何修复此错误以及该错误的含义。
英文:
I am getting error "not all arguments converted during string formatting" while running this code please explain how to fix this and what is this error
def multiples(l,n):
count=0
for i in l:
if(i%n==0):
count+=1
return count
m=input("no of elements: ")
l=[]
print("enter elements: ")
for i in range(int(m)):
l.append(input())
n=int(input("enter no to find no.of multiples: "))
print(multiples(l,n))
error:
Exception has occurred: TypeError
not all arguments converted during string formatting
line 4, in multiples
if(i%n==0):
line 13, in <module>
print(multiples(l,n))
TypeError: not all arguments converted during string formatting
答案1
得分: 0
问题在于您传递给 multiples
的列表 l
包含字符串而不是整数,这导致代码尝试在字符串上调用 %
运算符,而不是求模运算。由于 %
在字符串中通常用作格式化字符串的符号,所以您不会直接收到错误,就像 "% is my name" % name
一样。为了修复它,您可以将 input()
转换为整数,如下所示:l.append(int(input()))
因此,您的整体代码应该是这样的:
def multiples(l, n):
count = 0
for i in l:
if (i % n == 0):
count += 1
return count
m = input("元素数量:")
l = []
print("输入元素:")
for i in range(int(m)):
l.append(int(input()))
n = int(input("输入要查找的倍数:"))
print(multiples(l, n))
英文:
The problem is that the list l
that you are passing to multiples
has strings inside instead of int which causes the code to call %
on a string instead of modulo. You don't get a straightforward error as %
acts a format string like "% is my name" % name
. To fix it you can convert the input()
to int as so: l.append(int(input()))
so your overall code would be
def multiples(l,n):
count=0
for i in l:
if(i%n==0):
count+=1
return count
m=input("no of elements: ")
l=[]
print("enter elements: ")
for i in range(int(m)):
l.append(int(input()))
n=int(input("enter no to find no.of multiples: "))
print(multiples(l,n))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论