Date: Fri, 18 Aug 2006 17:54:01 +0200
Reply-To: Georg.Maubach@dpwnbc.net
Sender: "SPSSX(r) Discussion" <SPSSX-L@LISTSERV.UGA.EDU>
From: Georg Maubach <Georg.Maubach@dpwnbc.net>
Subject: Visibility of Python Variables
Content-Type: text/plain; charset="us-ascii"
Hi All,
I have a general question on Python programming.
In a function variables need to be declared as global if I wanna use a
variable in the function that was defined outside the function. But if I
use it as a parameter to a function this is not necessary.
I include a simple script code explaining the question in more detail.
--------------------- cut --------------------
# Author: Georg Maubach
# Date : 16-Aug-2006
# File : VisibilityOfVariables.py
from turtle import *
width(10)
step = 100 # a global variable is defined
color("blue")
# Section 1: Code works
def triangle():
forward(step) # The global variable step which should not be visible
to the
left(120) # interpreter does not cause an error during program
run
forward(step) # although it should be addressable by the interpreter
left(120) # cause the global variable "step" was not introduced
to the
forward(step) # function "triangle" by using "global step".
left(120) # Why does this not raise an error?
triangle()
# Section 2: Code does not work
def rectangle():
forward(step)
left(90)
forward(step)
left(90)
forward(step)
left(90)
forward(step)
left(90)
step = step + change # Why does this not work? The variable was
# defined as before. Now it seems to be not
# visible. Why? What is the difference between
# Section 1 and 2?
left(60) # next rectangle
rectangle()
# eof #
--------------------- cut --------------------
The question is why do I have not to declare a global variable to be
used as function parameter whereas I have to declare this variable as
global if I want to assign another value?
Question to List-Owner:
My question is more general. Is it off-topic to ask these questions on
this list?
I am looking forward to hearing from you.
Best regards
Georg Maubach
Market Analyst