PDA

View Full Version : python functions



johnd
15-08-2011, 06:02 PM
Hi

Have been doing a little beginning learning in Python. All has gone quite well until trying to get my first function to work as in the code below:


#! /usr/bin/python

area=0.0

def Calc_area (width,height):
area = width*height
return area

width = float(input("width?"))
height = float (input("height?"))
Calc_area (width,height)

print area

It does not want to return the area from the function - what am I missing?

John

johnd
15-08-2011, 06:18 PM
If I leave out the line "area=0.0" an error regarding undefined variable is given. If I leave it in, the area variable retains it's global value.

Fifthdawn
15-08-2011, 06:28 PM
I havn't used python before so please forgive me if this doesn't work/solove your problem.

just from looking at the code wouldn't you have to call your method against something?

i.e instead of

Calc_area (width,height)
try

area=Calc_area (width,height)

johnd
15-08-2011, 06:38 PM
The above code calls the function fine and works out the area - it just does not get back to the main program.

johnd
15-08-2011, 08:56 PM
OK - you are of course right. I have not had any experience in any C like language before.

MushHead
15-08-2011, 09:17 PM
You've got to remember that in nearly all C-like languages, the two "areas" you' have in your example are in fact completely different. Not sure about the case with Python, though the behaviour you describe seems to confirm it.

So when you remove the "area=0.0" line, you are failing to declare the global "area" variable, so when you "print area", then "area" no longer exists. Similarly, since the "area" within Calc_area() only is in-scope within the function, it contains the calculated area temporarily, then it is thrown away at the "return" statement. So unless you actually use or assign the result of Calc_area(), then you're not achieving anything.