我正在编写一个 Python 脚本来从特定端口获取数据。
所以我有一个 while 循环,只要端口打开就可以获取我的数据。
在这个 while 循环中,我添加了一个变量,我们称它为 foo1
。
时间到了,我不想再获取任何数据。
伪代码如下所示:
foo1 = 0
try:
while True:
fetch data
foo1 = foo1 + 500
if time up:
break
finally:
close socket
print foo1
在我的 while 循环中 foo1
加起来正确。但是在循环之外
foo1
始终为零。你有什么想法吗?
只需将 foo1 与 coh0 交换 编辑:
import re
coh = [0]
nachricht = ' S="0" '
coh0 = 0
time = 0
try:
while True:
time += 1
coh = re.findall(r'\bS="\d"', nachricht)
coh_value = re.findall(r'\d', coh[0])
if coh:
if int(coh_value[0]) == 0:
coh0 = int(coh0) + 500
print coh0
if time == 10:
coh0 = int((int(coh0)/500)/120)
print "Here coh0 is zero again",int(coh0)
break
finally:
pass
print "Here coh0 is zero again",int(coh0)
最佳答案
线
coh0 = int((int(coh0)/500)/120)
有效地执行除以 60000 的整数除法——它可以等价地写成
coh0 //= 60000
如果coh0
在执行这行之前恰好小于60000,则之后为0。
Inside of my while loop
foo1
adds up correctly. But outside of the loopfoo1
is always zero.
这是一种非常具有误导性的描述正在发生的事情的方式。正如您自己注意到的,它在循环内已经为零。
关于python - 在 while 循环之外访问变量,Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11034989/