Calling A Function Inside 'for' Loop Throws A Nameerror
Solution 1:
You have to create a function object
before you can use it. In your case you call a function but it is not yet existing hence not defined. As Kevin said, define the function and then try to call it.
UPD: I cannot add comments so I update it here. Mark Lutz in his "Learning Python" book describes it in a great detail, how functions work, what def
does and what happens when you call a function. But I assume any other Python book will do the same.
UPD: It is not easy to write comments, so I update the answer.
As said the problem is that you define function after you call it. For example, let's assume I want to write a program which writes "Have fun, " + any name. For simplicity name is given in the program. Option 1: If I write the program like you did meaning 1) call a function 2) define a function I will get an NameError exactly like you get.
Program:
greet = 'Have fun, 'print(greet + name('John')) # I call a function 'name'defname(x): # I define a functionreturnstr(x)
The output will be:
Traceback (most recent call last):
File "C:/Users/nikolay.dudaev/Documents/Private/deffun2.py", line 3, in <module>
print(greet + name('John'))
NameError: name 'name' is notdefined
ALL that I need to do is change places of function definition and calling a function:
greet = 'Have fun, 'defname(x): # I define a functionreturnstr(x)
print(greet + name('John')) # I call a function 'name'
And now the output is:
======= RESTART: C:/Users/nikolay.dudaev/Documents/Private/deffun2.py =======
Have fun, John
>>>
Here you go!
Copy what you have after def
and paste it before your for
loop and it should work (though I did not try your code).
Post a Comment for "Calling A Function Inside 'for' Loop Throws A Nameerror"