# HG changeset patch # User Atul Varma # Date 1212707482 25200 # Node ID eaf4ddc3b0927bbccbdfcf6bbbb5288113429fe2 # Parent e260fb2db3e5f4823ca2701621bbfa2685f8951c Added section on global variables diff -r e260fb2db3e5 -r eaf4ddc3b092 PythonForJsProgrammers.txt --- a/PythonForJsProgrammers.txt Thu Jun 05 15:55:15 2008 -0700 +++ b/PythonForJsProgrammers.txt Thu Jun 05 16:11:22 2008 -0700 @@ -219,6 +219,36 @@ As in JavaScript, they're first-class citizens and can be passed around as parameters to other functions and so forth. +Global Variables +================ + +Python, like JavaScript, is lexically scoped when it comes to reading +variables. + +However, Python's scoping rules for assignment to undefined variables +works opposite to JavaScript's; instead of being global by default, +variables are local, and there is no analog to ``var`` or ``let``. +Rather, the ``global`` keyword is used to specify that a variable be +bound to global instead of local scope: + + >>> a = 1 # Define our global variable. + >>> def foo(x): + ... a = x + 1 # 'a' is a new local variable. + >>> def bar(x): + ... global a # Bind 'a' to the global scope. + ... a = x + 1 + >>> foo(5) + >>> a + 1 + >>> bar(5) + >>> a + 6 + +This is for the best: as it's well-known that global variables should +be used as sparingly as possible, it's better for a language +interpreter to assume that all new assignments are local unless +explicitly told otherwise. + Closures ========