0

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

4 回答 4

0
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}
于 2020-10-09T16:12:26.590 回答
0

您没有得到数字的平方,因为您的函数def squareEach(nums)返回最后输入的数字的平方。例如,如果您输入 1,2,3,4,它将返回 16,因为 4^2=16。将您的平方函数更改为此-

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

对于计算出的每个平方数,追加到列表并返回要打印的列表。

于 2020-10-09T15:57:53.787 回答
0
def squareEach(nums):
   square = []
   for number in nums:
       number = number ** 2
       square.append(number)
   return square

那应该可以解决您的功能。

于 2020-10-09T15:59:35.620 回答
0

这应该可以帮助你

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

于 2020-10-09T16:00:05.440 回答