用户输入列表的平方和和

Square and Sum of User Inputted List

我想打印用户输入列表的总和和平方版本。我能够得到总和,但不能得到打印出来的列表的平方。前任。 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()

你没有得到数字的平方,因为你的函数 def squareEach(nums) returns 平方输入的最后一个数字。例如,如果您输入 1、2、3、4,它将 return 16,因为 4^2=16。将您的平方函数更改为 this-

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

对于计算出的数字的每个平方,附加到列表和return要打印的列表。

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

这应该可以修复您的功能。

这应该对你有帮助

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

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}