Python How to Return value in while loop

纵然是瞬间 提交于 2020-05-08 14:57:52

问题


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)

Could you please help me?


回答1:


Simply take your

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

put it into a function like

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

and change your while loop to simply be

while 1:
    print(foo(ser))

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)



回答2:


u can try this one

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


来源:https://stackoverflow.com/questions/41633129/python-how-to-return-value-in-while-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!