0

Why does this code never goes in to "else" and print accordingly when the condition in "if" is not satisfied?

j=0
for i in data:
  if j<10:

    if i['product']['id'] == p_id:
        if (i['stop_price']!='None'):
            print("Order Type:" +  str(i['stop_order_type']))
            print("Stop Price: " + str(i['stop_price']))

        else:
            print("Order Type: " + str(i['order_type']))



        print("Limit Price: " + str(i['limit_price']))
        print("Side: " + str(i['side']))
        print("Size: " + str(i['size']))
        print("Unfilled Size: " + str(i['unfilled_size']))

        print("\n\n")

    j+=1

It prints the below output:

Order Type:stop_loss_order
Stop Price: 405.0
Limit Price: 400.0
Side: buy
Size: 1
Unfilled Size: 1



Order Type:None
Stop Price: None
Limit Price: 280.0
Side: sell
Size: 1
Unfilled Size: 0



Order Type:None
Stop Price: None
Limit Price: 300.0
Side: sell
Size: 1
Unfilled Size: 1

But the correct Output should be:

Order Type:stop_loss_order
Stop Price: 405.0
Limit Price: 400.0
Side: buy
Size: 1
Unfilled Size: 1



Order Type:Limit
Limit Price: 280.0
Side: sell
Size: 1
Unfilled Size: 0



Order Type:Limit
Limit Price: 300.0
Side: sell
Size: 1
Unfilled Size: 1
Prayank
  • 156
  • 1
  • 8

2 Answers2

1

Change 'None' to a bare None. You're comparing it to the string 'None', which is generally going to be False unless it actually is the string 'None'.

It should look like:

    if (i['stop_price'] != None):

Note that in the case of a comparison with None, it's slightly more efficient to do:

    if (i['stop_price'] is not None):

Thierry Lathuille points out that the latter is recommended by the PEP 8 Programming Recommendations. Both versions should behave the same.

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
  • 1
    You should rather do `if (i['stop_price'] is not None):`, see https://stackoverflow.com/questions/14247373/python-none-comparison-should-i-use-is-or – Thierry Lathuille May 01 '20 at 06:41
  • @ThierryLathuille They're equivalent in the case of `None`, although `is not` is probably a little faster. I was addressing the specific problem that prevented OP's code from running, and I didn't want to confuse the issue by changing the comparison operator. – Tom Karzes May 01 '20 at 07:00
  • I understand why you left it the way it was - maybe you could add the 'canonical' way to do it to your answer. – Thierry Lathuille May 01 '20 at 07:02
  • @ThierryLathuille Ok, I added a note per your suggestion. – Tom Karzes May 01 '20 at 07:10
0

Check the value and type of i['stop_price'] in line if (i['stop_price']!='None') and modify the condition accordingly.

Here you are trying to check the value of i['stop_price'] not to be equal to 'None' of type String which can always be True unless the actual value in i['stop_price'] is equal to 'None' of type String.

Achuth Varghese
  • 2,356
  • 1
  • 4
  • 18