[英]Using the same variable in two different functions
我有兩個功能:
def read_temp():
lines1, lines2 = read_temp_raw()
while lines1[0].strip()[-3:] != "YES":
time.sleep(0.2)
lines1, lines2 = read_temp_raw()
temp1 = calculate_temp(lines1)
temp2 = calculate_temp(lines2)
return temp1, temp2
def Temp_difference():
if temp1 > temp2:
print(temp1 - temp2)
else:
print(temp2 - temp1)
我想在Temp_difference
中使用temp1
和temp2
。 當我嘗試在read_temp
中全局添加變量時,我的 IDE (Pycharm) 說:“全局變量 'temp1/2' 在模塊級別未定義”。 我試過這樣做:
def Temp_difference(temp1, temp2):
print (abs(temp1-temp2))
我在這里沒有收到任何警告或錯誤,但我不知道這是否正確。 那么有沒有更好/正確的方法來做到這一點?
在您的Temp_difference()
function 中,您可以調用您的read_temp()
function。 然后您可以將返回的值保存為temp1
和temp2
變量。 這是代碼:
def Temp_difference():
temp1, temp2 = read_temp()
if temp1 > temp2:
print(temp1 - temp2)
else:
print(temp2 - temp1)
正如你所擁有的,你的變量是給定函數的本地變量。 您可以在其他函數中使用全局變量,方法是在為其分配值的每個函數中將其聲明為global
變量:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.