-1

It says I have invalid syntax at Sum += 1. If my code is incorrect what is a better way to go about counting how many even numbers are in a list?

def countEvens(listOfInts):
    '''
    - Returns an integer value representing the number of even numbers that
    exist in listOfInts.
    - Return 0 if listOfInts is not a list type or if no even number exists
    in listOfInts.
    - Note: elements in listOfInts can contain any data type.
    '''
    Sum = 0
    for x in listOfInts:
        if x % 2 == 0:
            return Sum += 1
    if type(listOfInts) != list:
        return 0
Drise
  • 4,310
  • 5
  • 41
  • 66
  • You're returning the count at the first match of a even number itself which is wrong. It should increment the counter for each number and should return at the end. The return statement should be outside of for loop. – bharath Mar 19 '18 at 18:06
  • 1
    The `return` keyword statement takes an expression, but while `Sum += 1` is a valid statement, it is not an expression. Expressions can be evaluated to a value. You can read more about expressions and statements [here](https://stackoverflow.com/questions/4728073/what-is-the-difference-between-an-expression-and-a-statement-in-python) – Patrick Haugh Mar 19 '18 at 18:09

2 Answers2

3

In Python you cannot return assignments. And Sum += 1 is an assignment, it assigns Sum + 1 to Sum.

In fact the return isn't just a SyntaxError it's also wrong (in a logical sense), so just remove it:

Sum = 0
for x in listOfInts:
    if x % 2 == 0:
        Sum += 1
return Sum

Alternatively you can use sum with a generator:

return sum(1 for value in listOfInts if value % 2 == 0)
MSeifert
  • 145,886
  • 38
  • 333
  • 352
0

The syntax error comes from this line, as you say

return Sum += 1

That's because (Sum += 1) is not a valid value to return from a function. It's a separate statement

Keeping your code as close as possible, try this

Sum += 1
return Sum

or, more simply

return Sum+1

As for a more pythonic approach

def countEvens(listOfInts):
    return sum( x % 2 == 0 for x in listOfInts )

does the entire thing

kdopen
  • 8,032
  • 7
  • 44
  • 52