Python while循环中如何返回值

标签 python while-loop

当将 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)

你能帮我一下吗?

最佳答案

只需拿走您的

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)

关于Python while循环中如何返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41633129/

相关文章:

javascript - 如何使用 While 循环继续更改元素

Python 计算字符串格式宽度字段中的零长度控制字符?

python - SOCIAL_AUTH_LOGIN_ERROR_URL 不起作用 Django 2.0.6

python - 独特的对称元素 Numpy 数组

c - (;;) 和 while(); 的作用是什么? C中的意思

Javascript 函数破坏了整个程序?

python - 避免在 multiprocessing.Pool worker 中使用全局变量来获取不可篡改的共享状态

python - Spyder python编辑器: turn off whole-line tab when tabbing mid-line

c - 二进制打印在 C 中不起作用

PHP MySQL 循环/Foreach