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

Python程序报错求助:TypeError与NameError问题排查

Fixing Your Python Errors: TypeError and NameError

Let’s walk through the issues in your code and fix them one by one, with clear explanations of what went wrong.

1. NameError: "add" not found

The variable add lives only inside the sumList function—this is called a local scope. You tried to print add directly in main() without ever running sumList or saving its output to a variable that’s accessible in main().

Fix: Call sumList(nums) in main() and store the result in a variable (like total_sum) that you can then print.

2. TypeError: sumEach() missing 1 required positional argument: 'nums' + NameError: "squared" not found

Two problems here:

  • You never called sumEach with the nums argument, so Python throws a TypeError if you try to use it without passing the required parameter.
  • Even if you did call it, the squared variable is local to sumEach, so you can’t access it directly in main().
  • Bonus bug: The sumEach function as written ignores the nums parameter entirely—it just generates squares of numbers 1-5, which is almost certainly not what you wanted (you probably want to square each element in your input list).

Fix steps:

  • Rewrite sumEach to iterate over the input nums list instead of hardcoding 1-5.
  • Call sumEach(nums) in main() and store the result in a variable (like squared_list).

Corrected Code

Here’s the fixed version with comments highlighting key changes:

import math
import statistics

def main():
    numbers = str(input("Enter numbers separated by spaces: ")).split()
    nums = list(map(int, numbers))
    print("Original List", nums)
    
    # Call sumList with nums and store the total sum
    total_sum = sumList(nums)
    print("Sum of list: ", total_sum)
    
    # Call sumEach with nums and store the squared values
    squared_list = sumEach(nums)
    print("List squared", squared_list)

def sumEach(nums):
    squared = []
    # Iterate over each number in the input list (instead of hardcoding 1-5)
    for num in nums:
        squared.append(num ** 2)
    return squared

def sumList(nums):
    add = sum(nums)
    return add

main()

Example Output

If you run this code and enter 1 2 3 4, you’ll get:

Original List [1, 2, 3, 4]
Sum of list:  10
List squared [1, 4, 9, 16]

This resolves both errors and makes the code behave as intended.

内容的提问来源于stack exchange,提问作者Marvinman42

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:50:38