访问while循环外的变量Python

2024-05-16 17:59:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个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)

Tags: 端口retrueiftimeintprinttry
3条回答

线路

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.

这对描述正在发生的事情是一种误导。正如你自己注意到的,在循环中它已经是零了。

您的示例不起作用,因为您没有声明foo1的初始值,所以您引用它时没有它的存在-这将抛出一个NameError。如果您确实声明了初始值,则代码将工作:

>>> x = 0
>>> while True:
...    x += 1
...    if x > 10:
...        break
... 
>>> x
11

不仅如此,Python不会在while循环中使用名称空间,因此即使您的代码被修改为在while循环中使用y,它仍然可以工作:

>>> start = True
>>> while True:
...     if start:
...         y = 0
...         start = False
...     y += 1
...     if y > 10:
...         break
... 
>>> y
11

请注意,这是一个非常做作的例子,实际上很少有人想这么做。

请给我们一个Short, Self Contained, Correct, Example,它显示您的代码生成一个您不想要的结果,以及您想要的结果。因为您的问题根本不存在于Python中。

在循环之前必须声明foo1

foo1 = 0
while True:
    fetch data
    foo1 = foo1 + 500

在您的例子中,变量foo1仅在中具有可见性范围,而在循环中使用时,它只是在全局范围中再次创建。

相关问题 更多 >