Ashik Rabbani
Ashik Rabbani

Reputation: 27

Why if statement is executing while statement is false

Below this code if statement is executing and printing busy text when my frm and to value is not in in_line list. This a telephony system simulation problem.

I want that it will go to else statement when the value of frm and to not in in_line

call_list =[ 
         [1,    4,      38,     1050],
         [3,    5,      50,     1090]]



call_in_progress = [
         [1,    3,   1055],
         [2,   6,   1099]]



in_line = [1,3,2,6]

   while(len(call_in_progress)!=0):
        while(len(call_list)!=0):

    next_call = call_list[0]
    print("next call : ",next_call)
    Arrtival_time = next_call[3]

    frm,to = next_call[0],next_call[1]
    print(frm,to)
    print(in_line)
    if( frm or to in in_line ):

        print("busy")

        if(next_call[0] in in_line ):
            m_index = in_line.index(next_call[0])

            in_line.pop(m_index+1)
            in_line.remove(next_call[0])
            print(in_line)

        call_list.pop(0)
    else:
        np = [next_call[0],next_call[1],next_call[2]+next_call[3]]
        call_in_progress.append(np)
        call_list.pop(0)

   # print("prog ",call_in_progress)
    print("Completed ",call_in_progress.pop(0))

Upvotes: 0

Views: 96

Answers (2)

Chezzwizz
Chezzwizz

Reputation: 419

In Python, and in many other languages, the branching conditional test, such as is the case for if statements, requires the condition to be a statement (which can be a single expression). If multiple conditions need to be met, each condition is typically required to be a separate statement.

So in the case, such as you have presented where you want ensure that the frm and to items belong to the collection, each condition needs to be tested separately. To put it another way, the collection has to be tested against twice.

if to in in_line or frm in in_line:
    print("busy")

An easy way is to break down your tests into seperate if statements for each item you want to test. The preceding code would be the same as writing:

if to in in_line:
    print("busy")

if frm in in_line:
    print("busy")

For an AND conditional:

if to in in_inline:
    if frm in in_inline:
        print("busy")

As chepner indicated with their comment, the way the test is currently written first checks to see if frm is a truthy value and then checks to see if the to item is in the collection in_line.

Upvotes: 0

Draconis
Draconis

Reputation: 3461

Order of operations is tripping you up.

You currently have frm or to in line. But in is an operator, and or is a conjunction, and operators always come before conjunctions. So this gets interpreted as (frm) or (to in line).

Since frm is non-empty, it's treated as True, and the condition as a whole becomes true.

You want something like frm in line or to in line instead.

Upvotes: 1

Related Questions