Python Forum
Why is the if construct not calculating correctly?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why is the if construct not calculating correctly?
#2
once the if is satisfied, the remaining chain of elif's will not get executed. That's the way that it is intended.

If you want each statement to be executes, use a list of if's
the else is not necessary as you initialize sum to 0 before starting
Now, since sum is replaced each time, sum will be overwritten by the last successful if statement.

example:
def method1(e8, e13, e21, e55):
    sum = 0

    print(f"\nmethod1")

    if (e8 > e13):
        print(f"e8 > e13, so I'm done")
        sum = 1
    elif (e8 < e13):
        print(f"e8 < e13, so I'm done")
        sum = 0
    elif (e13 > e21):
        print(f"e813 > e21, so I'm done")
        sum = 1
    elif (e13 < e21):
        print(f"e13 < e21, so I'm done")
        sum = 0
    elif (e21 > e55):
        print(f"e21 > e55, so I'm done")
        sum = 1
    print(f"sum: {sum}")

def method2(e8, e13, e21, e55):
    sum = 0

    print(f"\nmethod2")
    if (e8, e13, e21, e55):
        print(f"e8 > e13")
        sum = 1
    if (e8 < e13):
        print(f"e8 < e13")
        sum = 0
    if (e13 > e21):
        print(f"e813 > e21")
        sum = 1
    if (e13 < e21):
        print(f"e13 < e21")
        sum = 0
    if (e21 > e55):
        print(f"e21 > e55")
        sum = 1
    print(f"sum: {sum}")

def main():
    method1(e8 = 1, e13 = 10, e21=6, e55 = 4)
    method2(e8 = 1, e13 = 10, e21=6, e55 = 4)

if __name__ == '__main__':
    main()
Output:
method1 e8 < e13, so I'm done sum: 0 method2 e8 > e13 e8 < e13 e813 > e21 e21 > e55 sum: 1 which is what should be expected.
Reply


Messages In This Thread
RE: Why is the if construct not calculating correctly? - by Larz60+ - Mar-19-2022, 01:54 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Building command in a looping construct DennisT 3 1,970 Sep-08-2020, 06:32 PM
Last Post: DennisT
  shortening an elif construct Skaperen 10 5,563 Jul-24-2018, 07:06 AM
Last Post: Skaperen
  Best construct? Array, class, other? PappaBear 1 3,013 May-10-2017, 06:02 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

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