python中局部变量和全局变量输出的混淆

时间:2016-02-17 07:09:49

标签: python global-variables local-variables

我是python的新手,正在尝试本地和全局变量。 'example1'产生输出'6,16,6',这是预期的。

x=6
def example1():
  print x
  print (x+10)
  print x  
example1()

在第二个例子中:

x=6
def example2():
   print x
   print (x+10)
print x  
example2()

我预计'6,16,6'为o / p,但得到'6,6,16'作为输出。有人可以在'example2()'中解释为什么会这样吗?

(我认为'example2'中的第二个'print x'语句指的是全局变量x(等于6),因此认为'6,16,6'应该是输出)

2 个答案:

答案 0 :(得分:1)

在第二个示例中,x的第一个值为6.然后,您调用方法example2(),首先打印x(即6),然后打x+10

所以输出将是:

6
6
16

为了更好地理解,以下是程序的执行顺序:

x=6
def example2():
   print x
   print (x+10)
print x  # this will be called first, so the first output is 6
example2() # then this, which will print 6 and then 16

答案 1 :(得分:0)

x=6
def example2():
   print x +"2nd call"
   print (x+10)
print x+" 1st call"  # This print gets call first
example2()

我认为这就解释了。第一次打印首先因为它的功能失效而在功能之前被调用 如果您希望输出为6,16,6,请按照以下方式制作字符

x=6
def example2():
   print x
   print (x+10) 
example2()
print x 
相关问题