[Tutor] Function behavior

Evert Rol evert.rol at gmail.com
Thu Sep 16 14:58:32 CEST 2010


> 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

Variables are only local to the their direct surroundings: in this case, amount is only local to the 'change' function, not outside it.

You might want to read through http://docs.python.org/tutorial/controlflow.html#defining-functions first.


  Evert


> 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
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor



More information about the Tutor mailing list