0

I want to print the sum and a squared version of an inputted list by a user. I am able to get the sum but not the list printed out squared. Ex. 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()
Tarik
  • 10,810
  • 2
  • 26
  • 40
RoG
  • 3
  • 1
  • 1
    While I realize this is an exercise in very rudimentary programming, you should also consider learning about built-in methods related to lists as well as list comprehensions as an ext step in your learning process. – itprorh66 Oct 09 '20 at 17:52
  • My advice is to do your homeworks on your own. Otherwise you will not learn. – Tarik Oct 10 '20 at 04:35

4 Answers4

0

You were not getting the square of the numbers because your function def squareEach(nums) returns the square of the last number entered. For ex, if you entered 1,2,3,4 it would return 16 since 4^2=16. Change your squaring function to this-

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

For every square of the number computed, append to the list and return the list to be printed.

Priyanka Rao
  • 208
  • 3
  • 11
0
def squareEach(nums):
   square = []
   for number in nums:
       number = number ** 2
       square.append(number)
   return square

That should fix your function.

Sumit Jaiswal
  • 216
  • 1
  • 4
  • 17
0

this should help you

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

bench
  • 136
  • 8
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}
Anmol Parida
  • 672
  • 5
  • 16