0

Hey guys, I have a question that I am a list of numbers and I need to use functions to find the average. I think I pretty much have it, but I can not get it to print the average. Can you please tell me what is wrong.

nums = [30,34,40,36,36,28,29,32,34,44,36,35,28,33,29,40,36,24,26,30,30,32,34,32,28,36,24,32]

def average(nums):
    return sum(nums) / len(nums)
1
  • The nums you are using in your def is not your list its a variable that will represent the argument you pass to the function. Commented Apr 12, 2011 at 21:20

2 Answers 2

4

Have you tried print average(nums)? The code you have so far is just defining the function. It isn't doing anything with it. You have to call the function with its parameters and then do something with its return value (i.e. use the print function).

Sign up to request clarification or add additional context in comments.

Comments

2

Basically your problem is this: int / int = int. You instead probably want one of these:

  • int / float = float
  • float / int = float

Try this:

nums = [30,34,40,36,36,28,29,32,34,44,36,35,28,33,
        29,40,36,24,26,30,30,32,34,32,28,36,24,32]

def average(n):
    return sum(n) / float(len(n))

print average(nums)

1 Comment

+1. From Python 2.5 or so you can do: from __future__ import division to have the / operator represent "true division" as opposed to "floor division"; more here: python.org/dev/peps/pep-0238

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.