2013-03-25 63 views
0

我正在学习python 3,通过观看一系列教程,
在其中一个关于可选函数参数(*args)的视频中,教师使用for循环打印传递给函数(元组)的可选参数。Python 3 - 打印错误*使用for循环

当我尝试运行教师的剧本,我得到一个错误:


教师脚本:

def test(a,b,c,*args): 
    print (a,b,c) 
for n in args: 
    print(n, end=' ') 

test('aa','bb','cc',1,2,3,4) 

OUTPUT:

C:\Python33\python.exe C:/untitled/0506.py 
Traceback (most recent call last): 
    File "C:/untitled/0506.py", line 4, in <module> 
    for n in args: print(n, end=' ') 
NameError: name 'args' is not defined 

Process finished with exit code 1 

def test(a,b,c,*args): 
    print (a,b,c) 
    print (args) 

test('aa','bb','cc',1,2,3,4) 

OUTPUT:

aa bb cc 
(1, 2, 3, 4) 
Process finished with exit code 0 

是什么造成的错误?
P.S:我正在使用Python 3.3.0。

回答

2

你有你的缩进错误:

def test(a,b,c,*args): 
    print (a,b,c) 
    for n in args: 
     print(n, end=' ') 

test('aa','bb','cc',1,2,3,4) 

缩进显著在Python;您的版本在test()函数的外部之外声明for n in args:循环,因此它立即运行。由于args仅为test()的局部变量,因此它不在函数的外部定义,因此您会得到NameError。 OMG!

+0

OMG!我真傻! 谢谢Martjin。 – 2013-03-25 18:27:54