Simple Clean Math Operations

99 Views Asked by At

I'm trying to make some basic methods for handling python math operations, I made a method for getting the sum of all numbers in the args like these:

def get_sum_of_numbers(*args):
    temp_value = 0
    for num in args:
        temp_value += num
    return temp_value

The problem is that when I try to create a simple average method:

def get_average_of_numbers(*args):
    return get_sum_of_numbers(args) / len(args)

I can't reuse this method because I can't just pass to the sum method the args of the average method as an argument, I want to make both the average method and the sum method take as many numbers as the programmer wishes to input. Anyone have any ideas?

2

There are 2 best solutions below

0
Spy_Banana On BEST ANSWER

put * before [args]

def get_average_of_numbers(*args):
    return get_sum_of_numbers(*args) / len(args)

and, yes, Tobi208 is right, You have incorrect indentation, see his answer, I don't want to steal his :)

0
Tobi208 On

You can use the * operator again

def get_average_of_numbers(*args):
    return get_sum_of_numbers(*args) / len(args)

Are you sure your get_sum_of_numbers function is doing what it's supposed to do though? Looks like it simply returns the value of the first arg. Why not do

def get_sum_of_numbers(*args):
    return sum(args)

or if you don't want to use sum

def get_sum_of_numbers(*args):
    temp_value = 0
    for num in args:
        temp_value += num
    return temp_value  # correct indentation