ASPN ActiveState Programmer Network
ActiveState
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups


Recent Messages
List Archives
About the List
List Leaders
Subscription Options

View Subscriptions
Help

View by Topic
ActiveState
.NET Framework
Open Source
Perl
PHP
Python
Tcl
Web Services
XML & XSLT

View by Category
Database
General
SOAP
System Administration
Tools
User Interfaces
Web Programming
XML Programming


MyASPN >> Mail Archive >> python-list
python-list
Re: Assigning to global variables from within a function
by W Isaac Carroll other posts by this author
Jul 12 2003 8:46PM messages near this date
Re: Assigning to global variables from within a function | Re: Help Support Python
Psymaster wrote:
>  I want to do this:
>  
>  int= 0
>  
>  def change_int():
>      	int += 1
>  
>  change_int()
>  
>  but of course it doesn't work, Python thinks it is a local 
>  variable and refuses to reference the global one. So what would 
>  be a good way of doing this. Note that creating a new global 
>  variable from within the function isn't convenient because the 
>  function is intended to be used in loops.

First of all, remember that "int" is a built-in, so it's not a good idea 
to use it for another purpose.

Have you tried declaring i as a global?

     i = 0

     def change_i():
         global i
         i += 1

     change_i()

This doesn't make a new global variable, it just tells the compiler that 
the i referenced inside the function is the global i, even though it's 
being assigned to.

TTFN


-- 
http://mail.python.org/mailman/listinfo/python-list
Thread:
Psymaster
Irmen de Jong
Psymaster
Tom Plunket
W Isaac Carroll

Privacy Policy | Email Opt-out | Feedback | Syndication
© ActiveState Software Inc. All rights reserved