[英]How can I import a variable from one function to another in Python?
我正在做一個項目,我需要導入一個在 function 中得到的變量,然后在另一個項目中使用它。 這是我正在嘗試做的一個例子。(這不是我的代碼,只是一個例子)
def interest(day,month,year):
interest = x #I got X by requesting a web data base.
def calc(debt,time):
result = (debt*x)/time
有沒有辦法將 X 從一個 function 導入另一個?
謝謝!
您考慮過上課嗎? 如果必須將變量傳遞給許多函數,則類非常有用。
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))
輸出: 30
如果您對使用類不感興趣,可以執行以下操作:
interest
和calc
而不是在interest
范圍內獲取 您不會將變量從一個函數導入另一個函數。 函數用於返回值和變量,您始終可以調用函數以獲取其返回值。 例如:
def interest(amt):
return amt * FIXED_INT
def calc(debt, time):
return debt * interest(debt) ** time
您可以將變量傳遞給參數
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)
這是我的操作方式:
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])
基本上,我在第一個函數中返回了sum1,因此當我在第二個函數中調用sum1時,sum1將被float(len(grades))除。 希望我能幫上忙! PS抱歉,格式文本難看,這是我的第一篇文章。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.