Python 编写演示局部变量和全局语句的简单程序有困难
我刚开始编程,我选择python作为我的第一语言。我在读关于局部变量和函数中的全局语句的书,我决定写一个简单的程序来练习。该程序的目标是从x=50开始,然后使用一个名为x的参数创建一个函数,将局部x更改为2,然后在不将全局x更改为3的情况下编写另一个函数。所以当我这样做并分别调用函数时,就像这样Python 编写演示局部变量和全局语句的简单程序有困难,python,Python,我刚开始编程,我选择python作为我的第一语言。我在读关于局部变量和函数中的全局语句的书,我决定写一个简单的程序来练习。该程序的目标是从x=50开始,然后使用一个名为x的参数创建一个函数,将局部x更改为2,然后在不将全局x更改为3的情况下编写另一个函数。所以当我这样做并分别调用函数时,就像这样 x = 50 def func(x): print 'x is', x x = 2 print 'Changed local x to', x func(x) print '
x = 50
def func(x):
print 'x is', x
x = 2
print 'Changed local x to', x
func(x)
print 'x is still', x
def func():
global x
print 'x is', x
x = 3
print 'Changed global x to', x
func()
print 'Value of x is', x
x=50
def func(x):
print 'x is', x
x = 2
print 'Changed local x to', x
def func():
global x
print 'x is', x
x = 3
print 'Changed global x to', x
func(x)
print 'x is still', x
func()
print "Value of x is", x
一切都很顺利。但是当我一个接一个地打电话时,就像这样
x = 50
def func(x):
print 'x is', x
x = 2
print 'Changed local x to', x
func(x)
print 'x is still', x
def func():
global x
print 'x is', x
x = 3
print 'Changed global x to', x
func()
print 'Value of x is', x
x=50
def func(x):
print 'x is', x
x = 2
print 'Changed local x to', x
def func():
global x
print 'x is', x
x = 3
print 'Changed global x to', x
func(x)
print 'x is still', x
func()
print "Value of x is", x
它不起作用。这是终点站
pedro@pedro-Inspiron-3521:~$ cd /home/pedro/Desktop/python
pedro@pedro-Inspiron-3521:~/Desktop/python$ python testperfect.py
x is 50
Changed local x to 2
x is still 50
x is 50
Changed global x to 3
Value of x is 3
pedro@pedro-Inspiron-3521:~/Desktop/python$ python test2.py
Traceback (most recent call last):
File "test2.py", line 18, in <module>
func(x)
TypeError: func() takes no arguments (1 given)
pedro@pedro-Inspiron-3521:~/Desktop/python$
pedro@pedro-Inspiron-3521:~$cd/home/pedro/Desktop/python
pedro@pedro-Inspiron-3521:~/Desktop/python$python testperfect.py
x是50
将本地x更改为2
x仍然是50岁
x是50
将全局x更改为3
x的值是3
pedro@pedro-Inspiron-3521:~/Desktop/python$python test2.py
回溯(最近一次呼叫最后一次):
文件“test2.py”,第18行,在
func(x)
TypeError:func()不接受任何参数(给定1个)
pedro@pedro-Inspiron-3521:~/Desktop/python$
。我做错了什么?我使用ubuntu作为操作系统,使用gedit作为文本编辑器,并在ubuntu中预装终端。Testperct.py是有效的文件,test2.py是无效的文件。Python。
所以,正如@Noble Mushtak和@bsoist所注意到的,先前定义的函数将被后来定义的函数覆盖
有关详细信息,请参阅。提示:如果定义两个同名函数,您认为会发生什么情况?您定义了两次
func()
,因此最后一个定义func()
——没有参数——将保留。因此,当调用func(x)
时,参数x
是意外的,会产生TypeError
。将第二个func()
定义为func2()
,然后使用func(x)
和func2()