5 its okay to be average. return errors


#1

my code (i'm just using the added bit to save scrolling time :blush:)

Add your function below!

def average(numbers):
-----total = float(sum(numbers))
result = total / float(len(numbers))
return result

is returning the following error

File "python", line 24
SyntaxError: 'return' outside function

however, when I do this

Add your function below!

def average(numbers):
-----total = float(sum(numbers))
result = total / float(len(numbers))
----return result

or this

Add your function below!

def average(numbers):
-----total = float(sum(numbers))
result = total / float(len(numbers))
-----return result

it returns

File "python", line 24
return result
^
IndentationError: unexpected indent

any help?


#2

So, I can see you don't understand how a function is structured.

A simple and common function in python is structured as follows

PYTHON CODE:

def simple_function(data): #  declare a function with its name
    return data   #  Do stuff and if you don't return something it returns None

If you know anything of Java or C, you can compare the white space to the {} that are require to encapsualte your code within a function.

C Code

int simple_function(int data)
{
    return data;
}

As you can see the {} is used to encapsulate the code to be executed, the same is done in python but with white space. It is vitally important to include the white space or the code will not function.


#3

how about this :smiley:
def average(numbers):
-----total = float(sum(numbers))
-----result = total / float(len(numbers))
-----return result


#4

Thank you!
That worked.


#5

sorry, that was a little rude.
please don't make assumptions like that.
I was having a small amount of difficulty with the functions, not having no idea of how they work.
Besides, if I didn't know how functions work, how would I have gotten this far in the course?:wink:


#6

This code also works:

def average(numbers):
total = float(sum(numbers)) / len(numbers)
return total


#7

Does too! Good to know! :blush:


#8

This code works:
def average(numbers):
total = sum(numbers)
total = float(total)
total = total / len(numbers)
return total


#9

Sorry, if the parameter numbers is a list, can the function sum() work?


#10

Add your function below!

def average(numbers):
total = float(sum(numbers))
length = len(numbers)
return total / length

code like up works


#11

thankyou @azazaz !! Worked


#12

the float in the total isn't needed as it is needed when dividing something.
Thus
def average(numbers):
-----total = sum(numbers)
-----result = total / float(len(numbers))
-----return result


#15