| Forum Home | ||||
| Press F1 | ||||
| Thread ID: 119886 | 2011-08-15 06:02:00 | python functions | johnd (85) | Press F1 |
| Post ID | Timestamp | Content | User | ||
| 1223387 | 2011-08-15 06:02:00 | 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 (85) | ||
| 1223388 | 2011-08-15 06:18:00 | 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. | johnd (85) | ||
| 1223389 | 2011-08-15 06:28:00 | 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) |
Fifthdawn (9467) | ||
| 1223390 | 2011-08-15 06:38:00 | The above code calls the function fine and works out the area - it just does not get back to the main program. | johnd (85) | ||
| 1223391 | 2011-08-15 08:56:00 | OK - you are of course right. I have not had any experience in any C like language before. | johnd (85) | ||
| 1223392 | 2011-08-15 09:17:00 | 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. |
MushHead (10626) | ||
| 1 | |||||