Reputation: 51
I'm working on a project and I need to import a variable that I got in a function and use it in another one. Here's an example of what I'm trying to do.(this is not my code, just an example)
def interest(day,month,year):
interest = x #I got X by requesting a web data base.
def calc(debt,time):
result = (debt*x)/time
Is there a way to import X from one function to another?
Thanks!
Upvotes: 1
Views: 18475
Reputation: 1
Here's how I did it:
def grades_sum(scores):
sum1 = 0
for i in scores:
sum1 = sum1 + i
print sum1
return sum1
grades_sum([100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5])
def grades_average(grades):
average = grades_sum(grades)/float(len(grades))
print average
return average
grades_average([100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5])
Basically, I returned sum1 in the first function, so that when I call it in the second function, sum1 will be divided by float(len(grades)). Hope I helped! P.S. Apologies for the ugly formatted text, this is my first post.
Upvotes: 0
Reputation: 6330
Have you considered using a class? Classes are extremely useful if you have variables that must be passed around to many functions.
class Foo:
def __init__(self):
pass
def set_x(self):
self.x = 5 # Whatever your source is!
def calculate_something(self, foo, bar):
return foo * bar * self.x
q = Foo()
q.set_x()
print(q.calculate_something(2, 3))
Output: 30
In case you aren't interested in using classes you could do the following:
interest
and calc
rather than fetching it within interest
Upvotes: 2
Reputation: 821
You can pass your variable into arguments
def interest(day,month,year):
interest = x
return interest
def calc(debt,time, interest):
result = (debt*interest)/time
...
x = interest(day,month,year)
calc(debt,time, x)
Upvotes: 0
Reputation: 17517
You don't import variables from a function to another. Functions are for returning values and variables, and you can always call a function to get its return value. For example:
def interest(amt):
return amt * FIXED_INT
def calc(debt, time):
return debt * interest(debt) ** time
Upvotes: 0