Python How to Return value in while loop

前端 未结 2 1472
星月不相逢
星月不相逢 2021-01-21 04:50

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(se         


        
相关标签:
2条回答
  • 2021-01-21 05:29

    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)
    
    0 讨论(0)
  • 2021-01-21 05:29

    u can try this one

    while 1:
        x=str(ser.readline())
        x = re.findall("\d+\.\d+", x)
        x = float(x[0])
    return x
    
    0 讨论(0)
提交回复
热议问题