1.2.4.5 全局变量

在函数外定义的变量可以在函数内引用:

In [18]:

  1. x = 5
  2. def addx(y):
  3. return x + y
  4. addx(10)

Out[18]:

  1. 15

但是,这些全局变量不能在函数内修改,除非在函数内声明global

这样没用:

In [19]:

  1. def setx(y):
  2. x = y
  3. print('x is %d' % x)
  4. setx(10)
  1. x is 10

In [20]:

  1. x

Out[20]:

  1. 5

这样可以:

In [21]:

  1. def setx(y):
  2. global x
  3. x = y
  4. print('x is %d' % x)
  5. setx(10)
  1. x is 10

In [22]:

  1. x

Out[22]:

  1. 10