Python如何在while循环中返回值 [英] Python How to Return value in while loop
本文介绍了Python如何在while循环中返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当将 return 放入 while 循环时,循环将停止如何解决?
When put return in while loop the loop will stop How to fix it?
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 循环更改为
and change your while loop to simply be
while 1:
print(foo(ser))
但是@developius 有一个更好的解决方案,看起来像
However @developius had a better solution which would look something like
while 1:
x=str(ser.readline())
x = re.findall("\d+\.\d+", x)
x = float(x[0])
print(x)
这篇关于Python如何在while循环中返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文