mardi 24 novembre 2020

Is there a clean way to check a variable inside a loop on the first iteration only or before its execution?

My code is in Python, but this question goes for any programming language.

Basically, I have a loop that has a structure similar to this:

while True:
    if visual:
        print("Something meaningful")
    function1()
    function2()

The visual variable is determined by the user when he calls the script with CLI arguments, its a boolean. Basically, if set to True, the user gets visual feedback, if False, he doesn't.

The problem is that the loop is going to check that variable on every iteration, slowing down the execution slightly.

I therefore wondered if there is a clean way to avoid having to check if "visual" is True on every iteration, to somehow tell the program to check that variable only on the first iteration, since the variable can't change mid-loop.

I thought of doing something like this :

if visual:       
    while True:
        print("Something meaningful")
        function1()
        function2()
else:
    while True:
        function1()
        function2()

It works, but it doesn't seem like good practice at all.

What is the cleanest way to solve this problem ?

Aucun commentaire:

Enregistrer un commentaire