Python Forum
which is better for many (el)ifs in a loop?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
which is better for many (el)ifs in a loop?
#1
i have many ifs or elifs in the body of a loop. which is better for such a situation?

style A:
   while or for some loop:
        if condition1:
            action1
            continue
        if condition2:
            action2
            continue
        if condition3:
            action3
            continue
        if condition4:
            action4
            continue
or ...
style B:
   while or for some loop:
        if condition1:
            action1
        elif condition2:
            action2
        elif condition3:
            action3
        elif condition4:
            action4
as you can see, both styles result in the same condition tests and selected action based on those tests. when you have a situation like this that may be very long, which is the better way in Python? does it vary by version of Python? does it vary by number of different conditions and actions? does it vary by anything else? or would your answer be the same for all these cases?

i did a test of something like this in C a long time ago with maximum optimization and examined the compiled result and got essentially identical machine code. both i don't know how Python would deal with these cases or what i should even consider important.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Messages In This Thread
which is better for many (el)ifs in a loop? - by Skaperen - Dec-11-2018, 01:32 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020