Python Question

Why is my condition expression giving a syntax error?

def singleNumber(nums):
for num in set(nums):
return num if nums.count(num) != 2 #error occurs here

print(singleNumber([1,1,4,5,5]))


This follows the usual python condition expression format. I don't understand why it's giving me a syntax error here.

The purpose of this function is to find number that doesn't occur twice.

Answer

If you're going to execute a return, you must return something no matter what.

Hence you could try:

return num if nums.count(num) != 2 else None

However, that's not going to work since it will return on the first check rather checking all the elements for what you want. In any case, I'm not that big a fan of post-conditions so I'd probably rewrite it as:

if nums.count(num) != 2: return num

This basically does what you need in that, if you don't explicitly return something (i.e., all of the numbers occur twice), the caller gets None.

Comments