以10为基数的int()的错误“无效文字”不断出现

时间:2022-02-20 23:47:08

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:

我在写一个非常简单的程序,我想打印出100以下3和5的所有倍数的和,但是,一个错误一直在出错,说“以10为基数的int()无效文字”我的程序如下:

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.

非常感谢您的帮助。

3 个解决方案

#1


10  

The "" are the cause of these problems.

“”是这些问题的原因。

Change

改变

sum = ""

to

sum = 0

and get rid of

和摆脱

else:
 sum += ""

#2


7  

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

Python不是JavaScript:“”不会自动转换为0,而0不会自动转换为“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.

您的程序似乎还混淆了打印所有3和5的倍数和打印所有3和5的倍数的所有数字的列表。

#3


3  

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

我对Python不熟,所以我做了一些傻事;不管怎样,我想我已经算出来了。

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

print sum

#1


10  

The "" are the cause of these problems.

“”是这些问题的原因。

Change

改变

sum = ""

to

sum = 0

and get rid of

和摆脱

else:
 sum += ""

#2


7  

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

Python不是JavaScript:“”不会自动转换为0,而0不会自动转换为“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.

您的程序似乎还混淆了打印所有3和5的倍数和打印所有3和5的倍数的所有数字的列表。

#3


3  

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

我对Python不熟,所以我做了一些傻事;不管怎样,我想我已经算出来了。

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

print sum