Python Shell错误

时间:2012-09-13 18:24:39

标签: python

我一直在python shell-version 2.7.3中使用此代码,我收到此错误。代码似乎还可以,我不明白我哪里出错了。

这是错误:

Traceback (most recent call last):
      File "C:\Python27\problem8euler.py", line 25, in <module>
        num.append(int(char))
    ValueError: invalid literal for int() with base 10: ''  

这是我的代码:

string = # that really long number, edited out for page-width-sanity 

num = [] 

for char in string: 
    num.append(int(char)) 


answers = [] 


i = 0 

while i <= len(num) - 5: 
    k = i + 1 
    l = i + 2 
    m = i + 3 
    n = i + 4 
    prod = ( num[i] * num[k] * num[l] * num[m] * num[n]) 
    answers.append(prod) 
    i += 1 

print max(answers)

代码是Project Euler问题8的解决方案。

对于我出错的地方,我们将不胜感激。

1 个答案:

答案 0 :(得分:1)

string包含空格字符。您对int中的每个字符发送stringint(' ')失败:

>>> int(' ')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''

只需删除空格字符即可解决问题,或跳过string中的空格,如下所示:

string = '1 2'
num = [int(c) for c in string if not c.isspace()] 

[.. for ..]构造称为list comprehension。)