[Tutor] Functions !

Remco Gerlich scarblac@pino.selwerd.nl
Wed, 29 Aug 2001 08:04:12 +0200


On  0, Dutch <dutch@lilrc.org> wrote:
> I have a question about functions.  I hope I can ask this clearly (and get
> a clear answer too!)
> The last programming I did was in basic on my Commoidore 64 and functions
> almost seem like what I remember as "subroutines"...

They're similar, but better. You couldn't give parameters to subroutines.

> Anyway, Im reading through and typing in the examples.  Below is one such
> example and it works fine...
> 
> I dont understand the variables "c_temp" or "f_temp" since they are not
> used anywhere else.

That is the point. You can call these functions with one argument, like
celsius_to_fahrenheit(24), and then c_temp will have the value 24 *inside
the function*. It's used inside the function, then not needed again. It's
invisible outside.

> 1.
> I am -guessing- that the part of the program that calls on the function is
> sending a variable to be processed in the function and it is getting
> dumped in c_temp or f_temp. If thats the case, they why is it that the
> original variable is not used, in this case "temp"? 

It would have worked, until you changed the program. If you turn the code
that calls it into a function as well, then its "temp" is invisible to the
outside (and celsius_to_fahrenheit is outside).

And worse, what if you want to call the function from many different places,
all using different names for a variable like "temp"?

So you pass in the number as an argument (celsius_to_fahrenheit(temp)), and
the little function doesn't have to know anything about what is calling it.
That is a good thing. You want to make bits of code that don't care about
the exact way the other bits of code work.

> 2.
> I'm guessing here too that many parts of a program with all their
> different variables can call the funtion so no one absolute vaiable can be
> used so this "dummy" (c_temp or f_temp) is used and I must therefore be
> careful not to use the same label (variable) anywhere else in my program.

You can use it at other places just fine. It's only used inside this
function, and is totally invisible everywhere else. You can have many
functions using the same local variable names, Python won't get confused.

> Im trying to follow the program (reading it) and understand what is
> happening.  It just wasnt clear where this 2 new lables came from and how
> the program "knows" what is to be used there.

> def celsius_to_fahrenheit(c_temp):
>     return 9.0/5.0*c_temp+32

It "knows" what to use because in the first line, you give a name to the
variable. "def celsius_to_fahrenheit(c_temp)" means "define a function, to
be named celsius_to_fahrenheit, that takes one argument, and call that
argument c_temp inside this function".

> ...Are my guess at least close?  And would addeding "exit" at the end be
> helpful in anyway?

It exits at the end anyway.

-- 
Remco Gerlich