Python 如何在 while 循环中返回值

新手上路,请多包涵

当在 while 循环中放入 return 时,循环将停止如何解决?

 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)

请你帮助我好吗?

原文由 Juizy J. 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

只需将您的

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

把它放到一个函数中

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

并将您的 while 循环更改为

while 1:
    print(foo(ser))

然而@developius有一个更好的解决方案,看起来像

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

原文由 Dillanm 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果要将值连续传递到单独的代码段,可以使用 yield

您可以按如下方式修改您的代码:

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

然后调用函数。请注意,f 将是一个生成器,因此您必须按如下方式对其进行循环。

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

参考: 这里

原文由 asif 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题