[英]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.