简体   繁体   中英

number in a given range if loop python

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????

You are comparing with strings, not numbers.

if x > -1.0 and x < 1.0:
    pass

Will do the comparison on numbers.

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

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.

这也有效:

if abs(x) < 1.0

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM