Home > Blockchain >  Part of IF statement is True, but not the whole thing
Part of IF statement is True, but not the whole thing

Time:12-03

I'm doing a Codewars drill but I don't know how to solve it entirely.

Here's what I have so far

def special_number(number):
    special = '012345'
    strnum = str(number)
    for i in strnum: 
        if i in special: 
            return "Special!!"
        else:
            return "NOT!!"

The number I'm struggling to get around is "39"

3 is in the special numbers list so that part is True.

9 is not.

I know that it is reading the 3 first and seeing that it's in the special numbers so its returning Special!!. But, I want it to keep going and see that 9 is not in the special numbers list so ultimately it will return "NOT!!"

Is there some small tweak that I can make so that it does do what I want?

CodePudding user response:

As far as small tweak solutions goes, a common pattern is slightly counter-intuitive. Because return stops execution, we only return 'special' if none of the digits are non-special

for i in strnum: 
    if i not in special: 
        return "NOT!!"

return "Special!!"

CodePudding user response:

A return will immediately stop the function. If you want to iterate all values, then one option is to use all() function

special = '012345'

def special_number(number):
    global special
    strnum = str(number)
    return 'Special!!' if all(i in special for i in strnum) else "NOT!!"
  • Related