TAGS :Viewed: 6 - Published at: a few seconds ago

[ Control flux in python if/elif continue ]

I have a if/elif statement in Python, but I want to execute both commands next. I want to show AD0 and AD1 every second, but the code is just showing AD1 (Not entering on elif).

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import serial
from time import sleep
import datetime

now = datetime.datetime.now()

port = '/dev/ttyUSB0'
ser = serial.Serial(port, 9600, timeout=0)

while True:
    arquivo = open('temperatura.txt','r')
    conteudo = arquivo.readlines()
    now = datetime.datetime.now()

    data = ser.read(9999)
    if len(data) > 0:
        if 'AD0'in data:
            temp = data[4:7]
            #print 'Got:', data
            #string = str('A temperatura é',temp,'ºC')             
            conteudo.append(now.strftime("%Y-%m-%d %H:%M"))
            conteudo.append(' ')
            conteudo.append('[AD0]A temperatura é')
            conteudo.append(temp)
            conteudo.append('ºC')           
            print '[AD0]A temperatura é',temp,'ºC'
            #print string 
            conteudo.append('\n')
            arquivo = openarquivo = open('temperatura.txt','w')
            arquivo.writelines(conteudo)
            continue

        elif 'AD1'in data:
            temp = data[4:7]
            #print 'Got:', data
            #string = str('A temperatura é',temp,'ºC')             
            conteudo.append(now.strftime("%Y-%m-%d %H:%M"))
            conteudo.append(' ')
            conteudo.append('[AD1]A temperatura é')
            conteudo.append(temp)
            conteudo.append('ºC')           
            print '[AD1]A temperatura é',temp,'ºC'
            #print string 
            conteudo.append('\n')
            arquivo = openarquivo = open('temperatura.txt','w')
            arquivo.writelines(conteudo)   

    sleep(1)
    #print 'not blocked'
    arquivo.close()

ser.close()

Answer 1


Python will pick the first matching condition out of a series of if..elif.. tests, and will execute just that one block of code.

If your two tests should be independent and both should be considered, replace the elif block with a separate if statement:

if 'AD0'in data:
    # ...

if 'AD1'in data:
    # ...

Now both conditions will be tested independently and if both match, both will be executed.