用户输入列表求和正常但平方列表输出异常的技术问题
问题分析与修复方案
Got it, let's break down why your squared list isn't showing up correctly—your sum calculation works fine, but the squareEach function has a small but critical issue!
The Root Problem
Look at your squareEach function:
def squareEach(nums): square = [] for number in nums: number = number ** 2 return number
You initialize an empty square list, but as soon as you calculate the first number's square, you use return number—this exits the function immediately, so you only ever return the first element's square, not the full list of squared values. The rest of the loop never runs, and your empty square list never gets used!
Fixed Code
Here's the corrected version with explanations of the changes:
# No need for math module since we're using **2 for squares def sumList(nums): total = 0 for n in nums: total += n # Shorthand for total = total + n return total def squareEach(nums): square = [] for number in nums: square.append(number ** 2) # Add each squared value to the list return square # Return the full list after processing all elements def main(): print("This is a program that returns the sum of numbers in a list.") print() nums_input = input("Enter a list element separated by a comma: ") # Use list comprehension to convert input to integers—cleaner than manual loop nums = [int(x.strip()) for x in nums_input.split(',')] SumTotal = sumList(nums) Squares = squareEach(nums) print(f"Here is the sum of the list of numbers {SumTotal}") print(f"Here is the squared version of the list {Squares}") main()
Key Changes Made
- Fixed
squareEach: Instead of returning the first squared value, we append every squared number to thesquarelist, then return the entire list once the loop finishes. - Simplified input conversion: Used a list comprehension to turn the comma-separated string into an integer list. Added
strip()to handle any accidental spaces (e.g., input like1, 2, 3will still work). - Removed unused
mathimport: You weren't using any functions from it, so it's safe to delete. - Minor readability tweak: Used
total += ninstead oftotal = total + n—it's standard Python shorthand for incrementing values.
Test It Out
If you input 1,2,3,4,5, you'll now get:
Here is the sum of the list of numbers 15 Here is the squared version of the list [1, 4, 9, 16, 25]
内容的提问来源于stack exchange,提问作者RoG
相关产品推荐
相关产品推荐

