You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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?

  1. 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 returns True, you won’t see it unless you explicitly output it.
  2. 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 None in this case, but you want it to return False instead.
  3. Unnecessary break: The break after return True does nothing—return immediately 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 False at the end of the function: This ensures that if no pairs sum to K, the function returns False instead of None.
  • Removed the redundant break after return True: Once return is executed, the function stops running, so the break is unnecessary.
  • Changed the call to print(funcSum()): This displays the returned True or False value 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:01:47