语法错误:输入错误 - Python

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16023333/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:38:13  来源:igfitidea点击:

Syntax error: bad input - Python

pythonarrayssyntax-error

提问by Jd Baba

I have this code:

我有这个代码:

num = range(1,33)
num[0]=1
num[1]=2
for i in range(2,32):
    num[i]=num[i-1]+num[i-2]


total=0
for i in range(0,32):
    print num[i]
    if num[i]%2==0:
    total=total+num[i]
    else:
    num[i]=num[i+1]

I want to find the sum of the even numbers in the numarray. Can anyone suggest what I did wrong here ?

我想找到num数组中偶数的总和。谁能建议我在这里做错了什么?

采纳答案by karthikr

Indentation is very important in python

缩进在python中非常重要

if num[i]%2==0:
total=total+num[i]
else:
num[i]=num[i+1]

should be

应该

if num[i]%2==0:
    total=total+num[i]
else:
    num[i]=num[i+1]

Also, use consistent indentation e.g 4 spaces every where you have to introduce indentation.

此外,使用一致的缩进,例如在每个必须引入缩进的地方使用 4 个空格。

回答by Thanakron Tandavas

Alternatively:

或者:

total = sum([i for i in num if i % 2 == 0])

For example:

例如:

>> num = [1,2,3,4]
>> tmp = [i for i in num if i % 2 == 0]
>> print tmp
[2,4]

>> total = sum(tmp)
>> print total
6