0
votes

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.

3
Print the return value ; print(funcSum())Smart Manoj
Yes, you can return in a loop. You're not printing the result of calling the functionOneCricketeer
You have to put the break then return the value from outside the loopRomain
how do you check if it works? because it should. also the break after the return is not neededblues
Note: you don't need a break after a return, and you should return False outside the loopOneCricketeer

3 Answers

1
votes

As others have said, there's nothing at all wrong with returning True the way that you are doing so. Seems to me that you're just missing returning False if you never find a match. I think you just want this:

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

    return False

funcSum()

I took out the break that you had in there. That line was unreachable code, and therefore unnecessary.

Your code could work as-is depending on what you're doing with the return value. My addition causes 'False' to be returned rather than 'None' in the case where you never match and return 'True'. In many cases, testing for "falseness" will succeed with a value of either False or None, so you might have been OK anyway. But adding the explicit return is very much recommended in any case...it insures that your function will always return a boolean value (either True or False).

0
votes

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 :)

-2
votes

It's not a good practice to break a for loop -- or at least it's something I try to avoid. So I think one clearer way to do it is to leverage on some existing tools (itertools.combinations, any), to avoid writing all the algorithm -- but, as highlighted by other users, it's perfectly fine to use break in your for loop.

import itertools

def func_sum2(num_list, k):
  """Return true if at least the sum of one combination of 2 elements in the list is equal to k.

  Use 
    - `itertools.combinations` to get the list of all combinations of 2 elements in the list
    - `any` to return true when at least one of the elements is Truth

  """
  return any(comb[0] + comb[1] == k 
         for comb in itertools.combinations(num_list, 2))

# Some tests
assert func_sum2([1,2], 3) == True
assert func_sum2([1,2], 4) == False
assert func_sum2([1,2,3], 5) == True

Note

I've skipped in the answer above the part related to get user's inputs to test it more efficiently. So your original code in this format is

def func_sum(num_list, k):
    answer = False

    for i in range (len(num_list)):
      for j in range(i + 1, len(num_list)):
        if num_list[i] + num_list[j] == k:
          answer = True
          break
    return answer

# Some tests
assert func_sum([1,2], 3) == True
assert func_sum([1,2], 4) == False
assert func_sum([1,2,3], 4) == True