Sam
Sam

Reputation: 499

Python 3 - Error in printing *args using for loop

I'm learning python 3 by watching a series of tutorials,
In one of these videos which is about optional function arguments (*args), the instructor uses a for loop to print the optional parameters passed to the function (the tuple).

When I try to run the instructor's script, I get an error:


Instructor's script:

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  

What's causing the error?
P.S: I'm using Python 3.3.0.

Upvotes: 0

Views: 205

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1125068

You got your indentation wrong:

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)  

Indentation is significant in Python; your version declared the for n in args: loop outside of the test() function, so it was run immediately. Since args is a local variable to test() only, it is not defined outside of the function and you get a NameError.

Upvotes: 2

Related Questions