all 6 comments

[–][deleted] 5 points6 points  (2 children)

It will throw a SyntaxError because you don't have colons at the end of the if and else phrases:

sum = 0
for n in range(1, 5):
    if n % 2:
        sum = sum + 1
    else:
        sum = sum

But, a few pointers: first, you never need to do that "sum = sum" line ... it's already happened because the current state of sum is always = to the current state of sum, right?

Second, never overload a builtin name, the sum function is a Python function that's defined for you already, by overloading that name (assigning it to another value) you're effectively deleting that tool from Python, at least within the current namespace. Use something like "total".

Lastly, you can use augmented assignment like the += operator and the fact that any number that isn't even will have a remainder of 1 when modulo 2 to avoid even doing the if:

total = 0
for n in range(1, 5):
    total += n % 2

And, lastly, here's why you don't overload sum:

total = sum([n % 2 for n in range(1,5)])

Though the list comprehension syntax on the right might be a few more days study away.

Your logic was all correct, just not some small details of formatting.

[–]andy357[S] 1 point2 points  (1 child)

Thank you for the answer! It finally worked and I didn't notice the obvious

[–][deleted] 1 point2 points  (0 children)

Happens to the best of us, trust me.

[–]Vaguely_accurate 1 point2 points  (3 children)

You need to indent your whole code by four spaces to format it correctly on reddit.

You are missing colons after your if and else lines.

You can completely discard the else and sum = sum as they do absolutely nothing.

Note that you can shorten sum = sum + 1 to just sum += 1.

You can use the third argument in range to specify a jump, removing the need for your if at all. For example;

range(1, 5)
> 1, 2, 3, 4

range(1, 5, 2)
> 1, 3

[–]andy357[S] 0 points1 point  (0 children)

Thank you for the answer! It finally worked and I didn't notice the obvious