Home > Enterprise >  Want To find a particular number in a list , True/False. Loop isn't iterating. Can someone expl
Want To find a particular number in a list , True/False. Loop isn't iterating. Can someone expl

Time:06-08

x = [1,9,9,9,9,2,3,4,5,6,7]

def consec_123(nums):
   for i in range(0, len(nums)):
        if nums[i] == 2:
            return True
        else:
            return False
pass

#The result comes out as False, even though there is 2 on the list. A reply would be highly appreciated.

CodePudding user response:

You have additional tab in else statement. In consec_123 case the else is else-if statement, in consec_Correct the else is for-else statement

x = [1,9,9,9,9,2,3,4,5,6,7]
def consec_Correct(nums):
    for i in range(0, len(nums)):
        if nums[i] == 2:
            return True
    else:
        return False
pass
print (consec_Correct(x))


def consec_123(nums):
    for i in range(0, len(nums)):
        if nums[i] == 2:
            return True
        else:
            return False
pass
print (consec_123(x))

Print output :

True
False

You can see step by step what is happening here

  • Related