Python如何在while循环中返回值

2024-09-30 01:25:55 发布

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

当将返回放入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)

你能帮帮我吗?


Tags: reloopreadlinereturnporttimeoutserialfloat
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)

你可以试试这个

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

相关问题 更多 >

    热门问题