def anshu():
a=1+2
print(a)
anshu()
def sanju():
b=2+3
print(b)
sanju()
def bala():
c=a+b
print(c)
can you explain?
I gave many value in one or more function i want use these value in any function in python
To access a variable from one function in another function, you can either return the variable from the first function and pass it as an argument to the second function, or you can make the variable global so that it can be accessed from any function. Here's an example using the first approach:
def anshu():
a = 1 + 2
return a
def sanju():
b = 2 + 3
return b
def bala(a, b):
c = a + b
print(c)
anshu_result = anshu()
sanju_result = sanju()
bala(anshu_result, sanju_result)
Here's an example using the second approach:
def anshu():
global a
a = 1 + 2
def sanju():
global b
b = 2 + 3
def bala():
c = a + b
print(c)
anshu()
sanju()
bala()
Note that using global variables is generally not considered good practice, because it can make your code difficult to maintain and debug. It's usually better to use the first approach of passing variables as arguments to functions.
Related
I have a function that essentially acts as a look-up table:
function lookup(a::Int64, x::Float64, y::Float64)
if a == 1
z = 2*x + y
else if a == 2
z = 5*x - 2*y
else if a == 3
...
end
return z
end
The variable a essentially determines what the relation of z is.
This function however takes a while to compile and is also not the most efficient at run time.
Could you compile the function lookup only for one instance of a (say a=1)? It is unlikely that this function will called for all possible functions of a.
I believe that such a functionality would be similar to templated functions in C++.
Julia's compiler can only dispatch on the type of arguments, not their value, as the value is only known at runtime. You can cheat a little by creating a "value type", where different values of a variable act as a different type:
lookup(::Type{Val{1}}, x, y) = 2x+y
lookup(::Type{Val{2}}, x, y) = 5x-2y
a = 2
lookup(Val{a}, 2, 3)
# 4
If you want to use this approach, you should read https://docs.julialang.org/en/stable/manual/performance-tips/#Types-with-values-as-parameters-1 first, to make sure it does not create issues with type-stability.
Consider the following piece of code.
def foo(a):
b = [a+9*i+j for i in xrange(0,3) for j in xrange(0,3)]
return b.remove(a)
The code doesn't work. It returns an null. But if I do the following, it works.
def foo1(a):
return [a+9*i+j for i in xrange(0,3) for j in xrange(0,3)]
b = foo1(a)
b = b.remove(a) # This works
Why does the first snippet fail when the second one works?
.remove(...) does not return any value. According to official documentation
You might have noticed that methods like insert, remove or sort that only modify the list have no return value printed – they return the default None. This is a design principle for all mutable data structures in Python.
def next1():
x=1
def nest2():
x+=1
nest2()
return x
When I try to call the fucntion nest1(), it says "local variable 'x' referenced before assignment
". I want to access x which is declared at line 2 inside nest2(). What is the solution?
in your nested function you havent defined x. you need to pass x to it def nest2(x): plus you have an infinite loop in nest2() - it continually calls itself, and never returns a value.
Why not do it this way? or is there some reason it needs to be nested.
def nest2(value):
value +=1
return value
def next1():
x=1
nest2(x)
return x
I was wondering if it is possible to use the return function and get the variable name
p.s ^ help to rephrase the above line
If you do not understand, here is the code:
def foo():
return <get variable name here>
a = foo()
Therefore, it will return 'a' to the variable a, 'b' to the variable b and so on, which means
the variable will contain its name.
Is there a function to return the variable's name ?
Can you write what you need that for?
There is no way to do that as you wish. But you can:
- do that without return, just define variable outside the function
- return a dict like {'a': variable}
There are other possibilities, depends only what are you want to do.
IMPORTANT: this is ugly and is probably WRONG way to do what you wanna do. Show us the whole use case, so we'll be able to help you choose better solution.
It is almost possible. Lets consider this:
g = True
def foo(val):
a = 5
b = "abc"
return XXX
And you want XXX to be "g" when val is True, "a" if val is 5 and "b" when val is "abc". You can inspect local and global variables with locals() and globals():
g = True
def foo(val):
a = 5
b = "abc"
for k, v in locals().iteritems(): # this will iterate over {"a": 5, "b": "abc"}
if v == var: # or "is" if you want identity
return k
for k, v in globals().iteritems(): # this will iterate over {"g": True, "foo": <this function>}
if v == var: # or "is" if you want identity
return k
return <default value>
Of course, there may be many names with the same value, and random of that names will be returned, if any. For example, it both a and b would have value 5 and you pass 5 as val, there is no way to tell which of them will be returned.
I REPEAT. WHATEVER YOU'RE TRYING TO DO, THIS IS WRONG (WITH 99.999% PROBABILITY). THERE ARE SOME REALLY SPECIAL SITUATIONS, WHEN locals() AND globals() MAY COME HANDY, BUT I DON'T THINK THIS IS ONE OF THOSE SITUATIONS.
== EDIT ==
I finally understood that you want to get the name of variable you're binding. Probably some tampering with stack trace could help you, but again - this is WRONG.
every one. I was trying to use the method copy(), but I was really frustrated it seems that there was bug within my program. I was supposed to get ct=99 only instead of ct =0, when comparing c1 and c2, but it turns out there are so extra terms behind.
Just run the code , and you can immediately spot What that weird thing is. Thank you every one.
NB: This problem is a generic programming problem and has nothing to do with Fourvector.
import numpy as np
class FourVector:
""" This document is a demonstration of how to create a class of Four vector """
def __init__(self, ct=0, x=1, y=5, z=2, r=None):
self.ct = ct
self.r = np.array(r if r else [x,y,z])
def __repr__(self):
return "%s(ct=%g,r=array%s)"% ("FourVector",self.ct,str(self.r))
def copy(self):
return FourVector(self.ct,self.r)
c1=FourVector(ct=0,r=[1,2,3]) # Note: c1,c2 here are objects, we used __repr__ to make them printable
print c1
c2=c1.copy() #use method copy within object c1
c2.ct=99
print c2
When you are copying, you are passing two unnamed arguments to FourVector.__init__. Python interprets them positionally, so you are effectively calling:
FourVector.__init__(new_self, ct=self.ct, x=self.r, y=5, z=2, r=None)
r is still None, so new_self.r is assigned to be np.array([self.r, y, z]). This is why the array in c2 has extra terms.
Instead, you need to tell Python that the second value should be for the r argument, not just the second argument:
def copy(self):
return FourVector(self.ct, r=self.r)
Alternatively, you could either re-order the arguments:
def __init__(self, ct, r=None, x=1, y=5, z=2):
or even remove the x, y and z arguments and provide them as the default value for r:
def __init__(self, ct, r=[1,5,2]):