I just create the function (Python) and want to use the variable that was defined outside the function and an error has occurred  def outside_variable_show(status):     if status == 1:         crrnt_nmbr = crrnt_nmbr + 1         print (crrnt_nmbr)  status = 1 crrnt_nmbr = 0 print (crrnt_nmbr) outside_variable_show(1)   note: "crrnt_nmbr" must use in and outside the function.  please tell me the way to implementation with it. Thank you so much.
4613
How can I create or use a global variable in a function?  If I create a global variable in one function, how can I use that global variable in another function? Do I need to store the global variable in a local variable of the function which needs its access?
42864
I mean other than using it when required for functions, classes, if, while, switch, try-catch.  I didn't know that it could be done like .  In the above link, Eli mentioned that "They use it to fold up their code in logical sections that don't fall into a function, class, loop, etc. that would usually be folded up."  What other uses are there besides those mentioned?   Is it a good idea to use curly braces to limit the scope of your variables and expand the scope only if required (working on a "need-to-access" basis)? Or is it actually silly?   How about using scopes just so that you can use the same variable names in different scopes but in the same bigger scope? Or is it a better practise to reuse the same variable (if you want to use the same variable name) and save on deallocating and allocating (I think some compilers can optimise on this?)? Or is it better to use different variable names altogether?
26511
I’m looking for a trick about this. I know how to call a dynamic, arbitrary function in JavaScript, passing specific parameters, something like this:  function mainfunc(func, par1, par2){     window[func](par1, par2); }  function calledfunc(par1, par2){     // Do stuff here }  mainfunc('calledfunc', 'hello', 'bye');   I know how to pass optional, unlimited parameters using the arguments collection inside mainfunc, but, I can’t figure how to send an arbitrary number of parameters to mainfunc to be sent to calledfunc dynamically; how can I accomplish something like this, but with any number of optional arguments (not using that ugly if–else)?  function mainfunc(func){     if(arguments.length == 3)         window[func](arguments[1], arguments[2]);     else if(arguments.length == 4)         window[func](arguments[1], arguments[2], arguments[3]);     else if(arguments.length == 5)         window[func](arguments[1], arguments[2], arguments[3], arguments[4]); }  function calledfunc1(par1, par2){     // Do stuff here }  function calledfunc2(par1, par2, par3){     // Do stuff here }  mainfunc('calledfunc1', 'hello', 'bye'); mainfunc('calledfunc2', 'hello', 'bye', 'goodbye');
74496
Please advise how to pass parameters into a function called using setInterval.  My example setInterval(funca(10,3), 500); is incorrect.
4188
While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python:  flist = []  for i in xrange(3):     def func(x): return x * i     flist.append(func)  for f in flist:     print f(2)   Note that this example mindfully avoids lambda. It prints "4 4 4", which is surprising. I'd expect "0 2 4".   This equivalent Perl code does it right:  my @flist = ();  foreach my $i (0 .. 2) {     push(@flist, sub {$i * $_[0]}); }  foreach my $f (@flist) {     print $f-&gt;(2), "\n"; }   "0 2 4" is printed.  Can you please explain the difference ?    Update:   The problem is not with i being global. This displays the same behavior:  flist = []  def outer():     for i in xrange(3):         def inner(x): return x * i         flist.append(inner)  outer() #~ print i   # commented because it causes an error  for f in flist:     print f(2)   As the commented line shows, i is unknown at that point. Still, it prints "4 4 4".
69089
I have been quite confused by the definition of functions and their uses.. First of all can one define functions in a clear understandable way, with a clear explanation of their uses, how they work and what they do?  Also I have some specific questions regarding functions Let me give you a examples:   $y = f(x) \rightarrow$ This is one of the main reasons I have difficulties understanding functions... What does the above statement tell me, and if $y$ is a function why do we use $y=$ at all for a formula like $y = mx + b$ would it be the same as writing $f(x) = mx + b$?   Something like $y = x^2$ is apparently a function...... but where is the function name? Which is the input and which is the output? Lastly another example : Let me suppose $f =$ distance                         $f(t) = t^2$                         $f(2) = 4 \rightarrow$ Does this mean distance is $4$.. which is the input which is the output?   Mainly what I'm looking for in an answer is a clear and 'easy' explanation with examples to help me understand this new topic
53333
I am coding a small Python module composed of two parts:   some functions defining a public interface, an implementation class used by the above functions, but which is not meaningful outside the module.   At first, I decided to "hide" this implementation class by defining it inside the function using it, but this hampers readability and cannot be used if multiple functions reuse the same class.  So, in addition to comments and docstrings, is there a mechanism to mark a class as "private" or "internal"? I am aware of the underscore mechanism, but as I understand it it only applies to variables, function and methods name.
86426
The title says it all (I'm referring to the case, when writing for example an article to be published or something similar - something where the writing itself should also be of quality).  Example: "Let $A_1,A_2,\ldots,A_n$ be subsets of a set $L$ and $f:L\rightarrow L$. Then define $B=\cup_{i=0}^n A_i$ and $C=\cup_{i=1}^{\infty} f^i (A_2)$, where $f^i$ is $f$ iterated with itself $i$ times."  So (in this example), would it be a problem to use $i$ twice as an index variable the ranges over different sets ? Or is it ok to think of $i$ as being define like a (lets do a computer-science analogy) "local variable", that is only used to create the object "in" which it is defined ($B$ for example) and after the object is created, the variable is "freed" again (so it can be used again to define $C$) ?  If it is NOT okay to do that, when is it allowed to use the same symbol again, after its first use ? After half a page ? After two pages ? In index-heavy proofs one would very soon have finished all letters commonly used as indices, of one would always have to use a different letter. And indexing sets with letters like $x$ or $f$ seems even worse style to me (ok, maybe there are areas in math, in which this would be common practice, but I don't know any).
30442
Consider the following code:    def CalcSomething(a):     if CalcSomething._cache.has_key(a):       return CalcSomething._cache[a]     CalcSomething._cache[a] = ReallyCalc(a)     return CalcSomething._cache[a]   CalcSomething._cache = { }   This is the easiest way I can think of for simulating a 'local static' variable in python. What bothers me is that CalcSomething._cache is mentioned outside the function's definition, but the alternative would be something like that:    if not hasattr(CalcSomething, "_cache"):       setattr(CalcSomething, "_cache", { } )     inside the function's definition, which is really cumbersome.    Is there a more elegant way?    [EDIT] Just to clarify, this question is not about local function caches, as the example above might suggest. Here is another short example where a 'static local' might be handy:    def ParseString(s):     return ParseString._parser.parse(s)   # Create a Parser object once, which will be used for all parsings. # Assuming a Parser object is heave on resources, for the sake of this example. ParseString._parser = Parser()
100903
Most languages have naming conventions for variables, the most common style I see in shell scripts is MY_VARIABLE=foo.  Is this the convention or is it only for global variables?  What about variables local to the script?
14541
I have a pretty good understanding of Javascript, except that I can't figure out a nice way to set the "this" variable.  Consider:  var myFunction = function(){     alert(this.foo_variable); }  var someObj = document.body; //using body as example object someObj.foo_variable = "hi"; //set foo_variable so it alerts  var old_fn = someObj.fn;   //store old value someObj.fn = myFunction;   //bind to someObj so "this" keyword works someObj.fn();               someObj.fn = old_fn;       //restore old value   Is there a way to do this without the last 4 lines?  It's rather annoying...  I've tried   binding an anonymous function, which I thought was beautiful and clever, but to no avail:  var myFunction = function(){     alert(this.foo_variable); }  var someObj = document.body;        //using body as example object someObj.foo_variable = "hi";        //set foo_variable so it alerts someObj.(function(){ fn(); })();    //fail.   Obviously, passing the variable into myFunction is an option... but that's not the point of this question.  Thanks.
26687
Is there any way to make “private” variables (those defined in the constructor), available to prototype-defined methods?  TestClass = function(){     var privateField = "hello";     this.nonProtoHello = function(){alert(privateField)}; }; TestClass.prototype.prototypeHello = function(){alert(privateField)};   This works:  t.nonProtoHello()   But this doesn’t:  t.prototypeHello()   I’m used to defining my methods inside the constructor, but am moving away from that for a couple reasons.
29305
What does it mean to extend a function? Can someone please give an example?  Thanks in advance!
12708
In python, you can have a function return multiple values.  Here's a contrived example:  def divide(x, y):     quotient = x/y     remainder = x % y     return quotient, remainder    (q, r) = divide(22, 7)   This seems very useful, but it looks like it can also be abused ("Well..function X already computes what we need as an intermediate value.  Let's have X return that value also").  When should you draw the line and define a different method?
110498
That's it. If you want to document a function or a class, you put a string just after the definition. For instance:  def foo():     """This function does nothing."""     pass   But what about a module? How can I document what a file.py does?
58103
I was answering a question and this little inconsistency popped up.  Just wondering if anyone has come across it before, or if anyone knows why this happens.  A variable that is declared within some form of scoped element (if, for loop, etc.) shouldn't be available outside that scope.  i.e.  {     // accountNames variable is not available outside this scope     Set&lt;String&gt; accountNames = new Set&lt;String&gt; {'Test Account'}; }  system.debug(accountNames);   This debug statement fails with the message:      Variable does not exist: accountNames   However, if this is part of a query string being generated, the Database.query() call somehow has access to it.  String queryString = 'SELECT Id, Name FROM Account';  if(true) {     // accountNames variable is not available outside the `if` statement     Set&lt;String&gt; accountNames = new Set&lt;String&gt; {'Test Account'};     queryString += ' WHERE Name IN :accountNames'; }  // this debug will fail if you uncomment it // system.debug(accountNames);  // however the query somehow has access to it. // create an account called Test Account to prove it.  system.debug('queryString: ' + queryString); system.debug('queryString result: ' + database.query(queryString));   But, Salesforce is smart enough to know that it's not just some random string, so the following will fail:  // Alternatively, use a random string as the variable name, and salesforce  // is smart enough to know it's gibberish String queryString2 = 'SELECT Id, Name FROM Account';  if(true) {     queryString2 += ' WHERE Name IN :randomString'; }  try {     system.debug('queryString2 result: ' + database.query(queryString2));     system.assert(false); } catch (QueryException qe)  {     system.debug(':randomString is gibberish: ' + qe.getMessage()); }     Edit:  Interestingly, the :randomString is definitely calculated only when the query is executed.  String queryString3 = 'SELECT Id, Name FROM Account'; String queryString4 = 'SELECT Id, Name FROM Account';  if(true) {     // assign to query 3 before it has a value     queryString3 += ' WHERE Name IN :randomString';      // assign to query 4 after it has been declared     Set&lt;String&gt; randomString = new Set&lt;String&gt;{'Test Account'};     queryString4 += ' WHERE Name IN :randomString'; }  // both queries return correct results, regardless of when the variable was declared system.debug('queryString3 result: ' + database.query(queryString3)); system.debug('queryString4 result: ' + database.query(queryString4));   But it's not an open slather.  The following throws an error:  String queryString = 'SELECT Id, Name FROM Account WHERE Name = :someField'; someMethod(); system.debug('queryString result: ' + database.query(queryString));  void someMethod() {     String someField = 'Test Account';     system.debug('someField: ' + someField); }     Does anyone know why this is the case, or have an explanation why this would work?  As far as I can tell, at the time that the accountNames variable is in scope, no part of the code knows that it's anything other than a string.
4570
I'd like to call a function in python using a dictionary.  Here is some code:  d = dict(param='test')  def f(param):     print(param)  f(d)   This prints {'param': 'test'} but I'd like it to just print test.  I'd like it to work similarly for more parameters:  d = dict(p1=1, p2=2) def f2(p1, p2):     print(p1, p2) f2(d)   Is this possible?