Search code examples
pythonreturn-type

Is it possible to return True in for loop?


In this code, I am taking two numbers in the list and checking whether it is adding up to K. The only problem is that I am not able to return True.

but if I use the print function instead of return it works. Is there some constraint that I cannot use return type in for loop or conditions?

def funcSum():
    NumList = []

    Number = int(input("Please enter the total number of list elements: "))
    for i in range(1, Number + 1):
        value = int(input("Please enter the value of %d element : " %i))
        NumList.append(value)

    k = int(input("Enter the value of K: "))

    for i in range (Number):
        for j in range(i + 1, Number):
            if NumList[i] + NumList[j] == k:
                return True
                break
funcSum()

I want to return True if two numbers add up to K or it will return False.


Solution

  • if you want to use your original code :

    def funcSum():
        NumList = []
    
        Number = int(input("Please enter the total number of list elements: "))
        for i in range(1, Number + 1):
            value = int(input("Please enter the value of %d element : " %i))
            NumList.append(value)
    
        k = int(input("Enter the value of K: "))
        equal = False
        for i in range (Number):
            for j in range(i + 1, Number):
                if NumList[i] + NumList[j] == k:
                    equal = True
                    break
            if equal:
                break
        return equal
    

    but you can also do this with the last bit:

        equal = False
        for i in list(NumList):
            for u in list(NumList):
                if i == u:
                    equal = True
                    break
            if equal :
                break
    

    hope it helps :)