Python Forum
Method not printing total or average
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Method not printing total or average
#1
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.
Reply
#2
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_list
Also, a few other suggestions:
  1. Never use list or any other keywords/built-in function names as a variable. It makes things confusing and will cause trouble in the long run.
  2. You do not use your total variable assigned on line 2, so get rid of it.
  3. Similarly, there is no need for your keep_going variable on line 5 since you never modify that value. You could get rid of it and just use while True: for your loop on line 9.
  4. Ideally, you should avoid using the same name for a parameter (when definining a function) and an argument (when calling the function), like using num in lines 17 and 22 for example. It technically works in most cases, but can cause issues (like being unable to define the variable as global within the function) and can make reading/troubleshooting the code more difficult.
Reply
#3
Thank a lot for your help
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020