0
sv= 0.000324
if sv != 0.00002 and 0.00003 and 0.00004 and 0.00005 and 0.0002 and 0.0003 and 0.0004 and 0.0005 and 0.000003 and 0.04 and 0.000000090 and 0.000005 and 0.00003 and 0.000000090 and 0.0000003:
    print (sv)

instead of writing many ands or ors is there is a way to make this code shorter or more pythonic way ?

J87
  • 179
  • 1
  • 1
  • 9
  • 2
    What are you expecting this code to do? What it actually does is `((sv != 0.000002)) and 0.00003) and 0.00004 …`, so in the end, the result will be False if `sv == 0.000002`, and `0.0000003` otherwise. – abarnert May 30 '18 at 17:58
  • 1
    Create a list and do `if sv not in list_` – rafaelc May 30 '18 at 17:58
  • 1
    ``if sv not in (your, values, here):`` ? a set would be even better than a list/tuple: ``if sv not in {your, values, here}`` – Mike Scotty May 30 '18 at 17:59
  • 1
    What hasn't been mentioned is that a set can be used to check more quickly. `if sv not in {your, values, here}:` – ChootsMagoots May 30 '18 at 17:59
  • 1
    You mean do what you probably meant to do or what the code actually does? – Fred Larson May 30 '18 at 18:00
  • 3
    It's probably better to use a set rather than a list. It will be a few nanoseconds faster, but, more importantly, what you're doing is conceptually asking "is this value a member of this set of values?" So, `if sv not in {0.0002, 0.0003, }:` – abarnert May 30 '18 at 18:01
  • 3
    Besides the problem explained in those duplicate questions, your real code may have another problem: you probably created `sv` with some kind of calculation, rather than just `sv = 0.000324`, right? In that case, you can't have exactly `0.000324` in a `float`—the closest values are (roughly) `0.000324000000000000014` and `0.00032399999999999990656`. And if you test `0.000324000000000000014 != 0.000324` you get `False`, but `0.00032399999999999990656 != 0.000324` is `True`. You generally do not want to test `float` values with `!=`. – abarnert May 30 '18 at 18:08
  • abarnert, yeah this is another problem, You generally do not want to test float values with != , then how to test them ? – J87 May 31 '18 at 06:50

1 Answers1

2

Put all the values in a list and check not in. Example Below

sv= 0.000324
not_sv_list = [0.00002, 0.00003, 0.00004, 0.00005, 0.0002, 0.0003, 0.0004, 
        0.0005, 0.000003, 0.04, 0.000000090, 0.000005, 0.00003, 0.000000090, 0.0000003 ]
if sv not in not_sv_list:
    print (sv)
Subhrajyoti Das
  • 2,685
  • 3
  • 21
  • 36