Kunal
Kunal

Reputation: 23

Getting Typerror: not all arguments converted during string formatting

Given question - Given a list of 10 numbers, find the average of all such numbers which is a multiple of 3

num = []
newlist = []

for i in range(1, 11):
    num.append(input())


for i in num:
    if i%3==0:
        newlist.append(i)

length = len(newlist)

total = sum(newlist)

average = total/length

print(average)

Getting this type error below at line 9 i.e. if i%3==0

not all arguments converted during string formatting

Upvotes: 0

Views: 41

Answers (2)

Sunny Patel
Sunny Patel

Reputation: 8077

When you num.append(input()), the value of input() is a string. You need to first convert that to an int and handle any possible errors before continuing. One way to do this is to change it to:

num.append(int(input()))

Since all the values in num are strings, i % 3 tries to perform old-string formatting, which is not what you expect.

Upvotes: 1

ForceBru
ForceBru

Reputation: 44886

input() returns a string, so i%3 will actually perform printf-style string formatting. Since your input doesn't have any formatting specifiers, but the % operator's right operand is not empty, you get the error, because you attempted to format a sting that doesn't have enough formatting specifiers.

To solve this, convert your input to integers:

num.append(int(input()))

Upvotes: 2

Related Questions