I was wondering if there is anyway to set a variable from a function. Let me explain with the following code:  number = 0 print number  def number_parse():     number = number + 1     return number  print number number_parse() print number number = number_parse() print number   I get the following output:  0 0 0 1   So what I am really trying to ask is, is there a way to set a variable from a function without having to call it from the line:  number = number_parse()   Can I not define a variable's value just by calling the function? What if I would like to set multiple variables (e.g. number, number_2, number_3 etc)  I am new to python and can't seem to figure this one out
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?
52909
In order to return a value from a VB.NET function one can assign a value to the "Functions Name" or use "return value."  I sometimes see these inter-mixed in the same function.  Personally, I prefer the return.  My question is, what is the internal difference, if any, between the two?
17203
I need to know if a variable in Python is a string or a dict.  Is there anything wrong with the following code?  if type(x) == type(str()):     do_something_with_a_string(x) elif type(x) == type(dict()):     do_somethting_with_a_dict(x) else:     raise ValueError   Update: I accepted avisser's answer (though I will change my mind if someone explains why isinstance is preferred over type(x) is).  But thanks to nakedfanatic for reminding me that it's often cleaner to use a dict (as a case statement) than an if/elif/else series.  Let me elaborate on my use case.  If a variable is a string, I need to put it in a list.  If it's a dict, I need a list of the unique values.  Here's what I came up with:  def value_list(x):     cases = {str: lambda t: [t],              dict: lambda t: list(set(t.values()))}     try:         return cases[type(x)](x)     except KeyError:         return None   If isinstance is preferred, how would you write this value_list() function?
7441
Was there any reason why the designers of Java felt that local variables should not be given a default value? Seriously, if instance variables can be given a default value, then why can't we do the same for local variables?  And it also leads to problems as explained in :     Well this rule is most frustrating when trying to close a resource in a finally block. If I instantiate the resource inside a try, but try to close it within the finally, I get this error. If I move the instantiation outside the try, I get another error stating that a it must be within a try.      Very frustrating.
60984
If you want to use global functions and variable dynamically you can use:  window[functionName](window[varName]);   Is it possible to do the same thing for variables in the local scope?  This code works correctly but currently uses eval and I'm trying to think of how else to do it.  var test = function(){     //this = window     var a, b, c; //private variables      var prop = function(name, def){         //this = window         eval(name+ ' = ' + (def.toSource() || undefined) + ';');              return function(value){             //this = test object             if ( !value) {                 return eval('(' + name + ')');             }             eval(name + ' = value;')             return this;         };      };      return {         a:prop('a', 1),         b:prop('b', 2),         c:prop('c', 3),         d:function(){             //to show that they are accessible via to methods             return [a,b,c];         }     }; }();  &gt;&gt;&gt;test Object &gt;&gt;&gt;test.prop undefined &gt;&gt;&gt;test.a function() &gt;&gt;&gt;test.a() 1 //returns the default &gt;&gt;&gt;test.a(123) Object //returns the object &gt;&gt;&gt;test.a() 123 //returns the changed private variable &gt;&gt;&gt;test.d() [123,2,3]
12905
How do you get the  of two variables in Python?  For example, I have two variables that I expect to be strings. I want to test that only one of them contains a True value (is not None or the empty string):  str1 = raw_input("Enter string one:") str2 = raw_input("Enter string two:") if logical_xor(str1, str2):     print "ok" else:     print "bad"   The ^ operator seems to be bitwise, and not defined on all objects:  &gt;&gt;&gt; 1 ^ 1 0 &gt;&gt;&gt; 2 ^ 1 3 &gt;&gt;&gt; "abc" ^ "" Traceback (most recent call last):   File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unsupported operand type(s) for ^: 'str' and 'str'
101805
I am not familiar with PHP at all and had a quick question.  I have 2 variables pricePerUnit and InvoicedUnits. Here's the code that is setting these to values:  $InvoicedUnits = ((string) $InvoiceLineItem-&gt;InvoicedUnits); $pricePerUnit = ((string) $InvoiceLineItem-&gt;PricePerUnit);   If I output this, I get the correct values. Lets say 5000 invoiced units and 1.00 for price.  Now, I need to show the total amount spent. When I multiply these two together it doesn't work (as expected, these are strings).  But I have no clue how to parse/cast/convert variables in PHP.  What should I do?
11097
In Python, how do I get a function name as a string, without calling the function?  def my_function():     pass  print get_function_name_as_string(my_function) # my_function is not in quotes   should output "my_function".  Is such function available in Python? If not, any ideas on how to implement get_function_name_as_string, in Python?
19743
I know that it is defined such that there is no more than one y-value output for any given x-value input, but I"m wondering WHY it is defined that way? Why can't we apply everything we know about functions to equations that have more than one y-value output for any given x-value input?   In short, what is the benefit or reason to define a function this way?  At the same time, a little historical context would also be appreciated (i.e., when the concept originated and why).  Thanks,  Moshe
2152
What exactly are the Python scoping rules?  If I have some code:  code1 class Foo:    code2    def spam.....       code3       for code4..:        code5        x()   Where is x found?  Some possible choices include the list below:   In the enclosing source file In the class namespace In the function definition In the for loop index variable Inside the for loop   Also there is the context during execution, when the function spam is passed somewhere else. And maybe  pass a bit differently?  There must be a simple reference or algorithm somewhere.  It's a confusing world for intermediate Python programmers.
42221
A friend asked me last week how to enumerate or list all variables within a program/function/etc. for the purposes of debugging (essentially getting a snapshot of everything so you can see what variables are set to, or if they are set at all). I looked around a bit and found a relatively good way for Python:   #!/usr/bin/python                                                                                                                                                                                                                            foo1 = "Hello world" foo2 = "bar" foo3 = {"1":"a",         "2":"b"} foo4 = "1+1"  for name in dir():     myvalue = eval(name)     print name, "is", type(name), "and is equal to ", myvalue   which will output something like:   __builtins__ is &lt;type 'str'&gt; and is equal to  &lt;module '__builtin__' (built-in)&gt; __doc__ is &lt;type 'str'&gt; and is equal to  None __file__ is &lt;type 'str'&gt; and is equal to  ./foo.py __name__ is &lt;type 'str'&gt; and is equal to  __main__ foo1 is &lt;type 'str'&gt; and is equal to  Hello world foo2 is &lt;type 'str'&gt; and is equal to  bar foo3 is &lt;type 'str'&gt; and is equal to  {'1': 'a', '2': 'b'} foo4 is &lt;type 'str'&gt; and is equal to  1+1   I have so far found a partial way in PHP (courtesy of ) but it only lists all variables and their types, not the contents:   &lt;?php // create a few variables $bar = 'foo'; $foo ='bar'; // create a new array object $arrayObj = new ArrayObject(get_defined_vars()); // loop over the array object and echo variables and values for($iterator = $arrayObj-&gt;getIterator(); $iterator-&gt;valid(); $iterator-&gt;next())         {         echo $iterator-&gt;key() . ' =&gt; ' . $iterator-&gt;current() . '&lt;br /&gt;';         } ?&gt;   So I put it to you: how do you list all variables and their contents in your favorite language?    Edit by : I propose this question follows the spirit of a little "". If you do not agree, just edit and remove the tag and the link.
84933
How can I change the variable in $$\int_{0}^{1}\int_{0}^{1} \frac{x-y}{(x+y)^3} dxdy$$ to computer the value  I tried to let $u=x+y$ and $v=x-y$  But I have no idea for next step   Can you give me some suggestion,thank you!!!
33578
I'm learning the Python programming language and I've came across something I don't fully understand.   In a method like:  def method(self, blah):     def __init__(?):         ....     ....   What does self do?  What is it meant to be?  Is it mandatory?  What does the __init__ method do?  Why is it necessary? (etc.)  I think they might be OOP constructs, but I don't know very much.
37330
I am trying to get a number by counting how many points are in a shapefile. And this works, except I then am running into trouble using that number somewhere else. Eventually, I'll be using that count in some math (field calculator), but while debugging I'm running into an error that will end up causing me trouble later on.   This code:  TotalPoints = arcpy.GetCount_management(Path_Pts) arcpy.AddMessage("&gt;&gt;&gt;&gt; PROCESS: COUNT PATH POINTS {" + TotalPoints + "}")   gives this error:  TypeError: cannot concatenate 'str' and 'Result' objects   I tried casting it as a int, which it ALSO doesn't like:  TypeError: int() argument must be a string or a number, not 'Result'   So I've got a 'Result' object and need to turn it into a number.   How can I do that -- or is using the ArcPy function unnecessary or overly complicated here?
36942
Say I have a Python function that returns multiple values in a tuple:  def func():     return 1, 2   Is there a nice way to ignore one of the results rather than just assigning to a temporary variable? Say if I was only interested in the first value, is there a better way than this:  x, temp = func()
74496
Please advise how to pass parameters into a function called using setInterval.  My example setInterval(funca(10,3), 500); is incorrect.
3866
Is it possible to have static class variables or methods in Python? What syntax is required to do this?