-2

A for loop that adds all 4-digit even numbers one after another, printing the intermediate sum for every 100th number (i.e., at the index positions 99, 199, 299, ...) along with its index number. Here is my answer so far:

l = range(1, 1000, 2)
sum1 = 0
for i in range(len(l)):
    sum1 += l[i]
    if i % 100 == 99 and (len(l[i]) == 4):
        print(sum1, i)
print(sum1)

Here's the error I'm getting:

TypeError                                 Traceback (most recent call last)
<ipython-input-175-6ae4f990101a> in <module>
      4 for i in range(len(l)):
      5     sum1 += l[i]
----> 6     if i % 100 == 99 and (len(l[i]) == 4):
      7         print(sum1, i)
      8 

TypeError: object of type 'int' has no len()

Can anyone enlighten me of what I am doing wrong? Any help will be appreciated. Thanks!

Pinaypy
  • 37
  • 1
  • 8
  • What do you think the error message means? `len` refers to the number of elements in a container; a better option for an `int` is to check the magnitude. – JoshuaF Jun 09 '20 at 00:26
  • I read only the traceback. If you want to use len to check the number of digits of an int, you can first turn it into a string: len(str(my_int)) You're getting an error because a number doesn't have an actual length, only its visual representation does. – dominik Jun 09 '20 at 00:28
  • @dominik Am I on the right track? Is the len function correct to get only 4 digit numbers in the for loop? Sorry, I'm totally new to Python. – Pinaypy Jun 09 '20 at 00:39

2 Answers2

1

You can't measure the number of characters in an integer because it is not a string.

Use l[i] >= 1000 and l[i] <= 9999 to test if it is 4 digits long.

If you insist on checking the string, then len(str(l[i])).

mike.k
  • 3,277
  • 1
  • 12
  • 18
1

Basically, l[i] is an array of integers and by saying len(l[i]), you are measuring the length of an integer, which is undefined.

In your code, replace len(l[i]) with l[i] >= 1000. Or, if you absolutely have to check the length of a number, use len(str(l[i])).

I also want to mention that setting a variable equal to range(1,1000,2) is unnecessary.

sum1 = 0
for i in range(0, 1000, 2):
    sum1 += i
    if i % 100 == 99 and (i >= 1000):
        print(sum1, i)
print(sum1)
tersrth
  • 861
  • 6
  • 18
  • How do I test the code if this is adding all the 4-digit even numbers? My answer should display index positions 99, 199, 299, etc. I edited my code and it seems to be working now, but not completely sure `10000 99 40000 199 90000 299 160000 399 250000 499 250000` @PranavaGande – Pinaypy Jun 09 '20 at 00:58