Python循环中能否返回True?两数和为K的函数无法返回True问题
Fixing Your Two-Sum Function Issue
Great question! There’s no restriction on using return inside for loops or conditionals—your problem comes from two easy-to-fix issues in your code and how you’re calling the function. Let’s break it down:
What’s Going Wrong?
- You’re not using the returned value: When you call
funcSum()at the end, you don’t print or store the result. Even if the function correctly returnsTrue, you won’t see it unless you explicitly output it. - No fallback return for no matching pairs: If no two numbers add up to K, your loops finish and the function exits without returning anything. Python automatically returns
Nonein this case, but you want it to returnFalseinstead. - Unnecessary
break: Thebreakafterreturn Truedoes nothing—returnimmediately exits the entire function, so the loop stops anyway.
Corrected Code
Here’s the fixed version of your function, plus how to properly call it to see the result:
def funcSum(): NumList = [] Number = int(input("Please enter the total number of list elements: ")) for i in range(1, Number + 1): value = int(input(f"Please enter the value of {i} element : ")) 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 immediately when a match is found # If we exit the loops without returning, no pairs were found return False # Call the function and print the result print(funcSum())
Key Changes Explained:
- Added
return Falseat the end of the function: This ensures that if no pairs sum to K, the function returnsFalseinstead ofNone. - Removed the redundant
breakafterreturn True: Oncereturnis executed, the function stops running, so the break is unnecessary. - Changed the call to
print(funcSum()): This displays the returnedTrueorFalsevalue so you can see the result.
Now, when you run the code, it will correctly return True when a valid pair exists and False otherwise, and you’ll be able to see the output!
内容的提问来源于stack exchange,提问作者Dishant Mewada
相关产品推荐
相关产品推荐

