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