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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

You should rather do if (i['stop_price'] is not None):, see stackoverflow.com/questions/14247373/…
@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.
I understand why you left it the way it was - maybe you could add the 'canonical' way to do it to your answer.
@ThierryLathuille Ok, I added a note per your suggestion.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.