Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Scope of variable confusion
#11
When assigning a variable Python uses local scope unless otherwise directed.
check = 1
This code assigns 1 to the variable "check" in the local scope. If the variable does not exist it is created. If this code executes in global/module scope it creates a global variable. If it is executed inside a function it creates a local/function variable.

By default, assignment is to variables in the current (local) scope. You can use the global keyword to tell Python to assign a variable in the global scope instead of the local scope.

You can see variables that exist in surrounding scopes, but this does not override the "assign to local behavior". In your first post sample_fcn could print the global check, but it could not assign a new value to the global check.
check = 0

def sample_fcn():
    print(check)  # This would see the global variable check because Global scope surrounds Local scope (LEGB)

def other_fcn():
    check = 1  # This creates a local variable check

def and_another_fcn():
    global check  # This tells Python to use check from Global scope
    check = 1  # Sets value of check in Global scope
Your function raised an exception when it did the "check += 1" which expands to
check = check + 1
The "check =" creates a local, undefined variable named check. The "check + 1" tries to add one to the undefined check. When getting a value for check Python does not look at the global check because it found check in the local scope.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to create a variable only for use inside the scope of a while loop? Radical 10 1,749 Nov-07-2023, 09:49 AM
Last Post: buran
  Library scope mike_zah 2 849 Feb-23-2023, 12:20 AM
Last Post: mike_zah
  Variable scope issue melvin13 2 1,547 Nov-29-2021, 08:26 PM
Last Post: melvin13
  Variable scope - "global x" didn't work... ptrivino 5 3,053 Dec-28-2020, 04:52 PM
Last Post: ptrivino
  Python Closures and Scope muzikman 2 1,818 Dec-14-2020, 11:21 PM
Last Post: muzikman
  Block of code, scope of variables and surprising exception arbiel 8 3,431 Apr-06-2020, 07:57 PM
Last Post: arbiel
  Help with Global/Coerced Variable (Understanding Scope) Rev2k 6 3,528 Jan-09-2020, 03:43 AM
Last Post: Rev2k
  Solving a scope issue profconn1 4 2,607 Nov-01-2019, 07:46 PM
Last Post: profconn1
  Namespace and scope difference Uchikago 9 4,621 Jul-03-2019, 03:36 PM
Last Post: Uchikago
  what is scope for python? samexpert 2 2,250 Jun-24-2019, 01:03 PM
Last Post: metulburr

Forum Jump:

User Panel Messages

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