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()
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.