[Courses] [python] Lesson 3: variable scope

Akkana Peck akkana at shallowsky.com
Thu Jul 7 02:16:32 UTC 2011


Brad and Monique wanted to know about variable scoping. This is
a relatively advanced topic that will probably only make sense to
folks who have done a fair amount of programming in other languages.
So, beginners, feel free to skip this message -- you won't need it
for anything in this class.

Brad writes:
> count = 0 # Initialize the count variable and set it to zero
[ ... ]
> for i in wordlist :
>     count += 1
> 
> Quick question on that one, from one of those Perl slobs (ie, me) --
> I stuck in an initialization value for variable "count" because it
> felt awkward not to have anything -- I'm used to strict variable
> declarations in Perl (which yes, I know you technically don't have
> to use, but you'd be a dope not to). Is there an equivalent here?

Python doesn't have any way of formally declaring variables, or
restricting them to certain types (like saying i will always be an
integer). You create a variable by setting it, like i = 42, and
you can do that any time.

But in your example, you did need the initialization, because you
wouldn't be able to say "count += 1" if you hadn't already set count;
count += 1 means "take the current value and add 1 to it", so you'd
get a "not defined" error if you hadn't set count first. 

> And if not, how do you determine variable scope, or does such a
> concept even exist within Python?
> 
> I guess I might be getting ahead of things a bit.

For new programmers, variable scope basically means "if I create a
variable i inside my program, where in the program can I use it?"

Basically, you can use a variable any time after you first set it.
But when you throw in functions the scoping gets a bit complicated.
(I'll be covering functions in lesson 4, anyone who's not familiar
with them yet.)

Anyway, if you have a function, and you've set a variable i before
you call the function, then the function will see the variable by
that name -- but only for reading. If it ever tries to set it, you'll
end up with a local variable i which is not connected to the global
variable i.  If you want the function to be able to set the global
i, there's a "global" keyword you can use inside the function. 

As I said, it's confusing, and I've never found a good write-up on
it -- a lot of Python books seem to gloss over scoping entirely, and
most of what I just wrote, I determined empirically by trying it,
IMHO, it's one of the language's weakest points. Happily, you can
mostly avoid it by using objects and functions instead of globals.

	...Akkana


More information about the Courses mailing list