0

I am working with python and doing the following.

x = [1,2,3,4,5]

def function1():
  print(x)

function1()

I would think that I would get the error name 'x' is not defined but I do not, it prints the variable x even though it is not defined in the function. Why does python let me use variables that are defined outside of a function inside a function even though they have different scopes?

biw
  • 3,000
  • 4
  • 23
  • 40

3 Answers3

0

Basically you are setting x to a global variable.

x = "myString"

function global():
    print(x) // Global


function notglobal():
    y = "myOtherString"
    print(y) // Not Global

class myClass: 
    z = "notGlobal" // Not Global

    function printZ():
        print(z) // Global To class

print(z) // Not global so will error out
Bioto
  • 1,127
  • 8
  • 21
0

x is global, which means all functions can use it.

Thedudxo
  • 549
  • 3
  • 8
  • 22
0

I like the treatment offered by this blog post, which compares the described behaviour to Javascript's variable hoisting (although the blog uses the negative example to demonstrate it).

TML
  • 12,813
  • 3
  • 38
  • 45