Python 用户输入列表的平方和和

Python 用户输入列表的平方和和,python,python-3.x,list,numbers,math-functions,Python,Python 3.x,List,Numbers,Math Functions,我想打印用户输入的列表的总和和平方版本。我能算出总数,但不能算出列表的平方。例1,2,3,4,5。。。。1,4,9,16,25 import math #This defines the sumList function def sumList(nums): total = 0 for n in nums: total = total + n return total def squareEach(nums): square = [] for nu

我想打印用户输入的列表的总和和平方版本。我能算出总数,但不能算出列表的平方。例1,2,3,4,5。。。。1,4,9,16,25

import math

#This defines the sumList function
def sumList(nums):

   total = 0
   for n in nums:
      total = total + n
   return total

def squareEach(nums):
   square = []
   for number in nums:
        number = number ** 2
   return number

 
#This defines the main program
def main():

   #Introduction
   print("This is a program that returns the sum of numbers in a list.")
   print()

   #Ask user to input list of numbers seperated by commas
   nums = input("Enter a list element separated by a comma: ")
   nums = nums.split(',')

   #Loop counts through number of entries by user and turns them into a list
   List = 0
   for i in nums:
        nums[List] = int(i)
        List = List + 1

   SumTotal = sumList(nums)
   Squares = squareEach(nums)
 
 
   #Provides the sum of the numbers in the list from the user input
   print("Here is the sum of the list of numbers {}".format(SumTotal))
   print("Here is the squared version of the list {}".format(Squares))

main()

由于函数defsquareEach(nums)返回最后输入的数字的平方,因此无法获取数字的平方。对于ex,如果输入1,2,3,4,它将返回16,因为4^2=16。将你的平方函数改为这个-

def squareEach(nums):
   square = []
   for number in nums:
        number = number ** 2
        square.append(number)
   return square
对于计算出的数字的每一平方,将其附加到列表并返回要打印的列表

def squareEach(nums):
   square = []
   for number in nums:
       number = number ** 2
       square.append(number)
   return square
这将修复您的功能。

这将对您有所帮助

def平方(nums):
正方形=[]
对于NUM中的数字:
方形。追加(编号**2)
返回广场

当我意识到这是一个非常基础的编程练习时,你也应该考虑学习与列表相关的内置方法以及列表理解作为学习过程中的下一步。我的建议是自己做你的家庭作业。否则你将无法学习。
lst = [2,3,4,5,6,7]
dict_square = {}
list_square =[]

for val in lst:
    dict_square[val] = val**2
    list_square.append(val**2)

print(sum(lst))     # 27 using the sum inbuilt method
print(list_square)  # [4, 9, 16, 25, 36, 49]
print(dict_square)  # {2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49}