2013-03-25 65 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