python - 在 while 循环之外访问变量,Python

标签 python sockets variables loops while-loop

我正在编写一个 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 始终为零。你有什么想法吗?

只需将 foo1coh0 交换 编辑:

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 loop foo1 is always zero.

这是一种非常具有误导性的描述正在发生的事情的方式。正如您自己注意到的,它在循环内已经为零。

关于python - 在 while 循环之外访问变量,Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11034989/

相关文章:

python - 转换pyqt4.py文件使用

python - python中分类数据的层次聚类

c++ - 如何使用 Qt 阻止 tcp 套接字?

list - 哪种语言理解 'variable a = 0 , 20, ..., 300' ?

python - 我可以将 Python 控制台脚本放入子模块中吗?

python - 在Python中将字典保存到文件(替代pickle)?

javascript - 在 React Native 中通过 Navigator 传递套接字

python - 套接字流量字节重复(?)

c++ - 变量自身初始化

c++ - 整个程序的变量访问