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
sumEachwith thenumsargument, so Python throws a TypeError if you try to use it without passing the required parameter. - Even if you did call it, the
squaredvariable is local tosumEach, so you can’t access it directly inmain(). - Bonus bug: The
sumEachfunction as written ignores thenumsparameter 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
sumEachto iterate over the inputnumslist instead of hardcoding 1-5. - Call
sumEach(nums)inmain()and store the result in a variable (likesquared_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
相关产品推荐
相关产品推荐

