Reputation: 171
I'm trying to compute this simple expression in python:
if a number is bigger than -1.0 and smaller than 1.0 do something.
I tried this:
if x > '-1.0' and x < '1.0':
DoSomething
but it turns out that it evaluates only the second part (x < '1.0'). I also tried
if '-1.0' < x < '1.0':
DoSomething
but strangely I don't get what I want. Any suggestion please????
Upvotes: 3
Views: 15793
Reputation: 208425
As other answers have mentioned, you need to remove the quotes so that you are comparing with numbers rather than strings.
However, none of those answers used Python's chained comparisons:
if -1.0 < x < 1.0:
DoSomething
This is equivalent to if x > -1.0 and x < 1.0
, but more efficient because x
is only evaluated once.
Upvotes: 2
Reputation: 4413
What you are doing in that code is comparing x with the string value '-1.0' or '1.0', not the double value. Try the following:
if x > -1.0 and x < 1.0:
Upvotes: 1
Reputation: 19329
You don't want to put the numbers in quotes - that results in a string comparison, not a numeric comparison. You want
if x > -1.0 and x < 1.0:
DoSomething
Upvotes: 2
Reputation: 10670
You are comparing with strings, not numbers.
if x > -1.0 and x < 1.0:
pass
Will do the comparison on numbers.
Upvotes: 8