Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 views
in Technique[技术] by (71.8m points)

Declaring variables inside a function python

For some reason I keep getting error in my code stating that my variables have not been declared. This only happens when I try to declare them in a function and not outside.

example

x, y = 105,107 
print (x,y) 

the above line of code works and gives me the output 105 107

but when I do this below

def fun1():
  x, y = 105,107 
print (x,y) 

I get NameError: name 'x' is not defined

need help to understand what's happening.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One of the main utilities of functions is exactly the way they allow one to isolate variables - no worries about clashing names for the code in various functions - once a function works properly, it is done.

But if one needs to expose variables that populated inside functions to the outside world, it is possible with the keyword "global". Notice that this is in general considered bad practice, and even for small scripts, there are often better solutions. But, common sense should always be the rule:

def fun1():
   global x, y
   x, y = 105, 107

fun1()
print(x, y)

Note that your code had another incorrect assumption: code inside function bodies is not executed unless the function is called - so, in the example in your question, even if you had declared the variables as global, the print call would still raise the same error, since you are not executing the line that defines these variables by calling the function.

Now, you've learned about "globals" - next step is forget it exists and learn how to work with variables properly encapsulated inside functions, and when you get to some intermediate/advanced level, then you will be able to judge when "globals" might actually do more good than harm (which is almost never).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...