[Tutor] Function behavior

Alan Gauld alan.gauld at btinternet.com
Thu Sep 16 23:26:14 CEST 2010


"Ken Green" <beachkidken at gmail.com> wrote

>I am unclear on the behavior of using a function.

You certainly are!
Which tutorial are you working from?
You have several fundamental errors here, its hard to know
where to start.

> def change(amount):
>     if match == 1:
>         amount = 0
>     if match == 2:
>         amount = 0
>     if match == 3:
>         amount = 3

This function is called change and it has an input parameter called 
amount.
The parameter is like a local variable only visible inside the 
function.
Because there are no return statements in it it will always return the
default value of None - probably not what you want.

Inside the function you compare a variable called match - which is not
defined in the function so presumably will be found outside in the 
module
or global scope - to a number.
You then set the parameter amount to another number, one greater
than the test value. But since amount is the parameter and invisible
outside the function that will have no affect on anything outside the
function.

> match = raw_input("How many matches?: ")

Now we define the global variable match but set it to a string.
The change() function is expecting match to be a number.
Maybe we should convert it using int()?

> change(match)


This does nothing and since we don't assign the functions value
to anything the None that it returns is lost.

> print amount

amount is not defined anywhere at the global scope and
the amount parameter in the function is not visible outside
the function.

> How many matches?: 2
> Traceback (most recent call last):
>   File "/home/ken/Python262/TEST Function.py", line 13, in <module>
>     print amount
> NameError: name 'amount' is not defined

> Should it be def change(match) instead of def change(amount)?
> Perhaps, change(amount) instead of change(match)?

You need to go back to basics on how parameters and arguments
work (This is, I admit, a subtle concept when you first come across 
it)

> Perhaps, I need to add return somewhere?

Yes you probably do. You can do what you want without it but
its considered bad practice. Functions should reurn their results.

Try reading the functions and modules topic in my tutorial
to see if that helps.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/





More information about the Tutor mailing list