Python Forum
Understanding Scoping in Python
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Understanding Scoping in Python
#5
(Aug-06-2018, 05:16 PM)Windspar Wrote: Because global spam only brings in global scope variables. Not non local variables.

# This is global scope area
spam = "global scope"

def print_spam():
    print(spam)

# soon as you get into a function. It a local variable.
def spam_it():
    def update_spam():
        # grabs  spam from 1 layer down.
        nonlocal spam
        spam = "nonlocal"

    def update_global():
        global spam
        spam = "global scope change"

    print_spam()
    spam = "local"
    print(spam)
    update_spam()
    print(spam)
    update_global()
    print_spam()

spam_it()


Okay. Thanks Windspar for your explanation. I understand now.
Reply


Messages In This Thread
Understanding Scoping in Python - by yksingh1097 - Aug-06-2018, 10:26 AM
RE: Understanding Scoping in Python - by Windspar - Aug-06-2018, 02:24 PM
RE: Understanding Scoping in Python - by Windspar - Aug-06-2018, 05:16 PM
RE: Understanding Scoping in Python - by yksingh1097 - Aug-06-2018, 06:35 PM
RE: Understanding Scoping in Python - by nilamo - Aug-06-2018, 07:42 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Understanding venv; How do I ensure my python script uses the environment every time? Calab 1 2,354 May-10-2023, 02:13 PM
Last Post: Calab
  New to python/coding Need help on Understanding why this code isn't working. Thanks! mat3372 8 1,822 May-09-2023, 08:47 AM
Last Post: buran
  Understanding Python classes PythonNewbee 3 1,237 Nov-10-2022, 11:07 PM
Last Post: deanhystad
  Understanding Python super() for classes OmegaRed94 1 1,874 Jun-09-2021, 09:02 AM
Last Post: buran
  Better Understanding Of Object Orientation In Python JoeDainton123 3 2,524 Aug-30-2020, 02:49 PM
Last Post: deanhystad
  Understanding Python's Import Engine MysticaL 1 2,209 Feb-07-2020, 11:26 PM
Last Post: snippsat
  Help with understanding a python package pyhill00 4 3,091 Mar-21-2019, 12:42 AM
Last Post: Larz60+
  Understanding if Statements in Python Kathleen 1 2,465 Mar-05-2019, 07:55 PM
Last Post: Yoriz
  Weird scoping error Stef 3 2,907 Jan-20-2019, 04:36 PM
Last Post: Stef
  Python Iteration Understanding giteepag 3 2,761 Jul-26-2018, 02:23 PM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020