On Thu, Sep 16, 2010 at 08:18:45AM -0400, Ken Green <[email protected]>
wrote:
> I am unclear on the behavior of using a function. Below is a short
> code I wrote to print an amount out after inputting the number of
> match.
>
> # TEST Function.py
>
> def change(amount):
> if match == 1:
> amount = 0
> if match == 2:
> amount = 0
> if match == 3:
> amount = 3
>
> match = raw_input("How many matches?: ")
> change(match)
> print amount
>
> ERROR Message:
>
> 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
>
> How do I print out the amount of 0 if I input 2?
>
> Should it be def change(match) instead of def change(amount)?
>
> Perhaps, change(amount) instead of change(match)?
>
> Perhaps, I need to add return somewhere?
>
> Thanking you all in advance for your assistance.
>
> Ken
If you want to get value from a function you whould return it, from that
function. So, you should use something like next code:
def change(amount):
amount = -1 #
if match == 1:
amount = 0
if match == 2:
amount = 0
if match == 3:
amount = 3
return amount
match = raw_input("How many matches?: ")
amount = change(match)
print amount
And please note next thing. amount variable inside function's body is not the
same as amount outside.
You should read about variable scope (local/global variables).
--
Please, use plain text message format contacting me, and
don't use proprietary formats for attachments (such as DOC, XLS)
use PDF, TXT, ODT, HTML instead. Thanks.
_______________________________________________
Tutor maillist - [email protected]
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor