Tee Jones - 1 year ago 51

Python Question

I need the sum and average functions to be combined to make my code shorter. My teacher said i don't need to add a function for the average i can just print average by dividing sum/n..???? any help ? Thanks in advance

`import random`

def main():

random_numbers = [random.randrange(1,100)

for _ in range (10)]

print(random_numbers)

numbers = random_numbers

total = get_total(numbers)

print("Sum:", total)

average = get_average(numbers)

print("Average:", average)

def get_total(value_list):

total = 0

for num in value_list:

total += num

return total

def get_average(value_list):

return get_total(value_list)/len(value_list)

main()

This is an example of what the output should look like(i have the correct output btw)

`[58, 25, 15, 66, 26, 58, 50, 12, 75, 48]`

Sum: 433

Average: 43.3

Answer Source

You do not have to do the multiple return statements. You can print right from a function.

```
import random
def main():
random_numbers = [random.randrange(1,100)
for _ in range (10)]
print(random_numbers)
numbers = random_numbers
getInformation(numbers)
def getInformation(value_list):
total = 0
for num in value_list:
total += num
print("Sum: " + total)
print("Average: " +total/len(value_list))
main()
```