简体   繁体   English

如果循环python,在给定范围内的数字

[英]number in a given range if loop python

I'm trying to compute this simple expression in python: 我试图在python中计算这个简单的表达式:

if a number is bigger than -1.0 and smaller than 1.0 do something. 如果数字大于-1.0且小于1.0则执行某些操作。

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'). 但事实证明它只评估第二部分(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 : 但是,这些答案都没有使用Python的链式比较

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 x > -1.0 and x < 1.0 ,但效率更高,因为x仅计算一次。

这也有效:

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. 您在该代码中所做的是将x与字符串值'-1.0'或'1.0'进行比较,而不是double值。 Try the following: 请尝试以下方法:

if x > -1.0 and x < 1.0:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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