-2

Simple python script is giving error, what is wrong?

var ="first variable"
myfun(var)

def myfun(var):
    print(var)

Error -> NameError: name 'myfun' is not defined

John
  • 1
  • 4
    You might want to declare your function before calling it – vvilin Jan 08 '20 at 17:59
  • But why is it so? Afaik python code works if declaration is done after call – John Jan 08 '20 at 18:00
  • 4
    "Afaik python code works if declaration is done after call"—where did you get this idea? Does it look like it's correct based on the question you're asking? – ChrisGPT was on strike Jan 08 '20 at 18:01
  • @Chris you mean python would read my code from top to bottom and if def is after call then it won't work? – John Jan 08 '20 at 18:03
  • I don't understand why would someone downvote this question, isn't it an appropriate question? – John Jan 08 '20 at 18:05
  • @John Yes, exactly – APhillips Jan 08 '20 at 18:05
  • @Chris I have to do the `main` thing at the end to make it work? – John Jan 08 '20 at 18:07
  • You have to move your function declarations above where they are called. Python code is read from top to bottom. Thats just how Python works. The correct path would be to put your functions and classes into their own modules. –  Jan 08 '20 at 18:09
  • @Josh yes I understand it now but I want to do it this way only, I would have to do it with main right? – John Jan 08 '20 at 18:10
  • In that example the functions are still declared above where they are called. That example is about functions calling each other and isn't at all relevant to what you are experiencing. Not sure why this is even considered a duplicate of that because it isn't at all. If putting your main method code and your functions in the same file and having the functions declared last is that important to you start looking into other languages. –  Jan 08 '20 at 18:13
  • "I don't understand why would someone downvote this question, isn't it an appropriate question?"—two main reasons, I think: (a) it's a duplicate and (b) the title is awful. Please read [ask]. – ChrisGPT was on strike Jan 08 '20 at 18:41

2 Answers2

1

This thing is quite obvious though. Python reads the code line by line and not like C.

Just switch your two blocks i.e. definition of function and calling it.

var ="first variable"

def myfun(var):
    print(var)

myfun(var)

This should be good to go.

0

When python interpreter sees the statement myfun(var), the name myfun is not defined yet. You need to move this line after your function definition.

Shashank V
  • 10,007
  • 2
  • 25
  • 41