New rules for scope in a function?

Steve Gronicus at SGA.Ninja
Mon Feb 18 13:14:26 EST 2019

OK, I wrote:

x = "A"
print("x = " + x)

def f(y):
    print("x= " + x + "  y= "+ y)

and it worked, inspite of what I was seeing in my own program.  
How quick I am to blame Python. (:
When I isolate my function that stumped me, I will post it.

Ultrasound Technician Asks Pregnant Woman If She'd Like To Know Baby's Name

-----Original Message-----
From: Python-list < at> On
Behalf Of Chris Angelico
Sent: Monday, February 18, 2019 12:40 PM
To: Python <python-list at>
Subject: Re: New rules for scope in a function?

On Tue, Feb 19, 2019 at 4:36 AM Steve <Gronicus at> wrote:
> I have been programming for more years than I want to admit and believe
that I have a good understanding when it comes to the Scope of Variables
when using functions. Are the rules different when using python?
> It looks as if I have to pass all variables to and from the function
before it works.  Are variables used in the main program not also visible
for use within the function?  Do these variables have to be declared as
> Steve

Functions in Python have access to everything in the surrounding scopes,
usually a module. Any name that's ever *assigned to* in the function
(including its parameters) is local to that function, and anything that you
look up without assigning comes from the outer scope.

x = 1
def f(y):
    print(x, y)

This function is happily able to see its own parameter (a local) and the
name from outside it (a global). It's also able to see the "print"
function, which comes from the builtins - that's just another scope.


More information about the Python-list mailing list