Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

the error "invalid literal for int() with base 10:" keeps coming up

I'm trying to write a very simple program, I want to print out the sum of all the multiples of 3 and 5 below 100, but, an error keeps accuring, saying "invalid literal for int() with base 10:" my program is as follows:

sum = ""
sum_int = int(sum)
for i in range(1, 101):
    if i % 5 == 0:
        sum += i 
    elif i % 3 == 0:
        sum += i
    else:
        sum += ""

print sum

Any help would be much appreciated.

like image 438
user313022 Avatar asked Apr 12 '10 10:04

user313022


3 Answers

The "" are the cause of these problems.

Change

sum = ""

to

sum = 0

and get rid of

else:
 sum += ""
like image 197
codaddict Avatar answered Oct 08 '22 07:10

codaddict


Python is not JavaScript: "" does not automatically convert to 0, and 0 does not automatically convert to "0".

Your program also seems to be confused between printing the sum of all the multiples of three and five and printing a list of all the numbers which are multiples of three and five.

like image 28
Andrew Aylett Avatar answered Oct 08 '22 07:10

Andrew Aylett


Ok, I'm new to Python so I was doing quite a few silly things; anyway, I think I've worked it out now.

sum = 0
for i in range(1, 1001):
    if i % 5 == 0:
        sum += i 
    elif i % 3 == 0:
        sum += i

print sum
like image 29
user313022 Avatar answered Oct 08 '22 06:10

user313022