Variable value in while True

while True:
    lenreplay = len(mail.reply())
    print(lenreplay)
    if len(mail.reply()) > lenreplay:
        print('done')
        print(mail.reply()[0])

At some point the length of mail.reply() will no longer be what it was before. I want the if to work. Please note that if here in my code doesn’t always work. It only works if the computing process was between lenreplay = len(mail.reply()) and if len(mail.reply()) > lenreplay:. I want for it to always work.

mail.reply() is a group of emails inside a list. If I sent an email that list will get a new length, which means it will become bigger than it was before.

Any suggestions?

>Solution :

Is len(mail.reply()) checking the current number of replies to some mail? And you want this loop to continue until an additional reply has been received? Why not put lenreplay = len(mail.reply()) outside the loop and add a small delay (like time.sleep(1)) to avoid constantly checking?

I.e.:

from time import sleep

number_of_replies = len(mail.reply())
while True:
    print(number_of_replies)
    sleep(1)  # maybe wait a second here, to avoid spamming the call
    if len(mail.reply()) > number_of_replies:
        print('done')
        print(mail.reply()[0])
        break

I renamed the variable, since its previous name didn’t make that much sense. Also, I added break to exit the loop; if you didn’t have break because you want this to run forever, this would work:

from time import sleep

while True:
    number_of_replies = len(mail.reply())
    while True:
        print(number_of_replies)
        sleep(1)
        if len(mail.reply()) > number_of_replies:
            print('done')
            print(mail.reply()[0])
            break

Leave a Reply