11
def sum10(a, b):
    if sum([a, b]) % 10 == 0: return True; return False

print sum10(7, 3)
print sum10(-13, -17)
print sum10(3, 8)

the result is:

True
True
None

not what I expected:

True
True
False

any idea?

6 Answers 6

31

Your code

def sum10(a, b):
    if sum([a, b]) % 10 == 0: return True; return False

is equivalent to

def sum10(a, b):
    if sum([a, b]) % 10 == 0: 
        return True; return False

so return False is never evaluated.


Some (of the probably endless) alternatives:

    if sum([a, b]) % 10 == 0: 
        return True
    return False

or

    return sum([a, b]) % 10 == 0

or

    return True if sum([a, b]) % 10 == 0 else False

or

    return False if (a+b) % 10 else True

or (the most readable IMHO)

    return not (a + b) % 10
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Mr. Steak. one more question, could you make your "Better use 1" to one line?
@yozloy I added more examples.
10

This is what you want.

def sum10(a, b):
    return sum([a, b]) % 10 == 0

Also the ternary If in Python works like this

<True Statment> if <Conditional Expression> else <False Statement>

eg

True if sum([a,b]) % 10 == 0 else False

Might i also recommend using the plus operator?

True if (a+b) % 10 == 0 else False

1 Comment

Thanks for the ternary solution
3

If you want to have if-else one liners, they should be written like this:

return True if sum([a, b]) % 10 == 0 else False

Note the absence of two points in that one liner.

1 Comment

Thanks again for answering my question @alestanis, ternary is the way to go
1

I think that the return False is never executed due to it is into the if, not outside it.

So, when you take a true in the if condition, you are executing return True, but never the second statement.

1 Comment

+1 for good explanation of what it doesn't work, I think I should stick to ternary way
1
def sum10(a, b):
    return sum([a, b])%10 == 0

1 Comment

Some explanation here would not go unappreciated.
0

Instead of returning True or False right away, you could try storing result in a boolean variable and then return that variable at the end. For example:

def sum(a,b):
  bool result
  if sum([a, b]) % 10 == 0:
    bool=True
  else:
    bool=False
  return bool 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.