Method not printing total or average - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Method not printing total or average (/thread-29442.html) |
Method not printing total or average - SephMon - Sep-02-2020 The list is populated with user input but it doesn't print out the total when it sums all the numbers or average of list list = [] total = 0 num = 0 keep_going = True def get_input(): while keep_going: try: num = int(input("Please enter numbers into list or 0 to exit: ")) if num == 0: break list.append(num) except ValueError: print("VALUE MUST BE INTEGER! ") sum_array(num) calculate_average(num) print_answers(num, average) def sum_array(num): for nums in list: num += int(nums) def calculate_average(num): global average average = num / len(list) def print_answers(num, average): print(list) print("Total: ", num) print("Average: ", average) get_input()Any ideas? thanks. RE: Method not printing total or average - GOTO10 - Sep-02-2020 Your single biggest issue in terms of getting the results you want is that your sum_array(num) call on line 17 does not return a value or preserve the changes it makes to the variable num, so that value is still 0 when you make your function calls on lines 18 and 19. You would be better off passing your list to the function, returning the sum, and assigning that to a variable. (You could also use the built-in sum function if you are not specifically intending to avoid that - sum(list_of_numbers) will return the sum of a list of numeric values.) Once you have a variable containing the sum, you can use that in your other calls as needed.num_list = [1, 2, 3, 4] def sum_array(arr): value = 0 for num in arr: value += num return value my_sum = sum_array(num_list) #variable my_sum now contains the summed value of num_listAlso, a few other suggestions:
RE: Method not printing total or average - SephMon - Sep-02-2020 Thank a lot for your help |