简体   繁体   English

Python如何在while循环中返回值

[英]Python How to Return value in while loop

When put return in while loop the loop will stop How to fix it?当将 return 放入 while 循环时,循环将停止如何解决?

ser = serial.Serial(
    port='COM5',
    baudrate = 9600,
    timeout=1)
while 1:
    x=str(ser.readline())
    x = re.findall("\d+\.\d+", x)
    x = float(x[0])
    return(x) #loop stopped
    print(x)

Could you please help me?请你帮助我好吗?

Simply take your只需将您的

x=str(ser.readline())
x = re.findall("\d+\.\d+", x)
x = float(x[0])
return(x) #loop stopped

put it into a function like把它变成一个函数

def foo(ser):
    x=str(ser.readline())
    x = re.findall("\d+\.\d+", x)
    x = float(x[0])
    return(x)

and change your while loop to simply be并将您的 while 循环更改为简单地

while 1:
    print(foo(ser))

However @developius had a better solution which would look something like但是@developius 有一个更好的解决方案,看起来像

while 1:
    x=str(ser.readline())
    x = re.findall("\d+\.\d+", x)
    x = float(x[0])
    print(x)

If you want to pass the values continuously to a separate piece of code, you can use yield .如果要将值连续传递给单独的代码段,可以使用yield

You can modify your code as followed:您可以按如下方式修改您的代码:

def func():
    while 1:
        x=str(ser.readline())
        x = re.findall("\d+\.\d+", x)
        x = float(x[0])
        yield x

And then call the function.然后调用函数。 Note that f will be a generator so you will have to loop over it as below.请注意, f 将是一个生成器,因此您必须按如下方式对其进行循环。

f = func()
for i in f:
    print(i) # or use i for any purpose

Reference: here参考:这里

u can try this one你可以试试这个

while 1:
    x=str(ser.readline())
    x = re.findall("\d+\.\d+", x)
    x = float(x[0])
return x

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM