Python - 如果不是0.0的语句

时间:2016-02-23 08:44:26

标签: python python-2.7 if-statement control-structure

我对if not中的Python 2.7陈述有疑问。

我编写了一些代码并使用了if not语句。在我编写的代码的一部分中,我引用了一个包含if not语句的函数来确定是否输入了可选关键字。

它工作正常,除非0.0是关键字的值。我理解这是因为0是被认为是'不'的事情之一。我的代码可能太长而无法发布,但这是一个类似的(尽管是简化的)示例:

def square(x=None):
    if not x:
        print "you have not entered x"
    else:
        y=x**2
        return y

list=[1, 3, 0 ,9]
output=[]


for item in list:
    y=square(item)
    output.append(y)

print output

然而,在这种情况下我离开了:

you have not entered x
[1, 9, None, 81]    

我希望得到的地方:

[1, 9, 0, 81]

在上面的示例中,我可以使用列表推导,但假设我想使用该函数并获得所需的输出,我该怎么做?

我有一个想法是:

def square(x=None):
    if not x and not str(x).isdigit():
        print "you have not entered x"
    else:
        y=x**2
        return y

list=[1, 3, 0 ,9]
output=[]


for item in list:
    y=square(item)
    output.append(y)

print output

这样可行,但似乎有点笨拙的做法。如果有人有另一种方式会很好,我会非常感激。

6 个答案:

答案 0 :(得分:18)

问题

你理解得对。 not 0(以及not 0.0)会在True中返回Python。可以进行简单的测试以查看:

a = not 0
print(a)

Result: True

因此,解释了该问题。这一行:

if not x:

必须更改为其他内容。

解决方案

有几种方法可以解决问题。我只是将列出它们从我认为最好的解决方案到最后可能的解决方案:


  1. 处理所有可能的有效案件

    由于square应该自然地期望输入数字而排除复数,否则return会出现错误,我认为最好的解决方案是使用{{进行评估1}}

    if not isinstance(x, numbers.Number) or isinstance(x, numbers.Complex):

    numbers.Number 抽象类,用于检查参数def square(x=None): if not isinstance(x, numbers.Number) or isinstance(x, numbers.Complex): # this sums up every number type, with the exclusion of complex number print ("you have not entered x") else: y=x**2 return y list=[1, 3, 0 ,9] output=[] for item in list: y=square(item) output.append(y) print (output) 是否为数字(归功于Copperfield以指出这一点。)

    摘自Python Standard Library Documentation解释只是你需要什么 - 除了复数:

      

    class numbers.Number

         

    数字层次结构的。如果你只是想检查一下   参数x是数字,不关心什么类型,使用 isinstance(x,   数)

    但是,您不希望输入是复数。所以,只需使用x

    省略它
      

    通过这种方式,您可以像or isinstance(x, numbers.Complex) 一样完全编写definition   想要它。我认为,这个解决方案是凭借出色的最佳解决方案    全面性


    1. 仅处理您要处理的数据类型

      如果您有一个列表有效的inpug数据类型,您还可以将只提供您想要处理的那些特定数据类型。也就是说,您不希望处理除指定数据类型之外的数据类型的情况。例子:

      square
        

      您可以针对不同的数据更改/扩展 以上的条件   您希望包含或排除的类型 - 根据您的   需要。我认为,这个解决方案凭借其优势,是次佳    自定义有效性检查

      (上面的代码以更多 Pythonical 方式完成,如cat所示)


      1. 不处理不可能的案例:您知道用户将作为输入的内容。

        更宽松地思考,如果你知道 - 不是你想要处理的数据类型,就像在第二个解决方案中那样 - 但是用户放置的数据类型,那么你可以有更宽松的条件像这样检查:

        if not instance(x, int): #just handle int
        if not instance(x, (int, float)): #just handle int and float
        if not instance(x, (numbers.Integral, numbers.Rational)): #just handle integral and rational, not real or complex
        
          

        我认为这个解决方案是 一个   最简单但功能强大的检查

        此解决方案的唯一缺点是您无法处理复杂类型。因此,只能通过用户不会将复数作为输入来实现。


        1. 仅针对可能导致错误的已知可能输入处理输入错误

          例如,如果您知道x总是if not isinstance(x, numbers.Number): # this is ok, because the user would not put up complex number int - 因此唯一可能的输入错误是None - 那么我们可以简单地编写逻辑以避免{{当None yx时,正在评估

          None
            

          此解决方案具有 最简单的 的优点。

          ...但危险用于,如果您不知道完全用户将为输入提供什么。否则,这个解决方案很好,也是最简单的。

          您的解决方案,我认为或多或少属于此类别。您知道用户将提供什么输入以及用户不会提供什么。因此,使用此解决方案或您自己的解决方案:

          def square(x=None):
              if x is None:
                  print ("you have not entered x")
              else:
                 y=x**2
                 return y
          
          list=[1, 3, 0 ,9]
          output=[]
          
          for item in list:
              y=square(item)
              output.append(y)
          
          print (output)
          

          很好,除了示例解决方案更简单

        2. 根据您的情况,您可以使用上面的任何解决方案获取:

          if not x and not str(x).isdigit():
          

          (旁注:我尝试将解决方案格式化为"规范解决方案"以便于阅读。这样,那些有相同问题并且访问此页面的人未来可能能够找到更全面和可读的解决方案)

答案 1 :(得分:8)

由于您使用NSURLSessionConfiguration来表示"此参数未设置",这正是您应使用None关键字检查的内容:

is

检查类型很麻烦且容易出错,因为您必须检查所有可能的输入类型,而不仅仅是def square(x=None): if x is None: print "you have not entered x" else: y=x**2 return y

答案 2 :(得分:2)

if x is None:
   print 'x is None'

答案 3 :(得分:1)

据我所知,你想要抓住没有给出任何意见的案例:

if x is None:
    ...

以及它不是数字的情况。对于第二个问题,你最终会遇到一些问题,因为你可能希望将来允许numpy-ndarray或其他东西,通常我只是建议不要打扰排除其他类但是如果你只想允许intfloat然后使用

if isinstance(x, (int, float, ...)):
    ...

...代表其他允许的类别(可能是DecimalFractions)。

所以你可以把它写成:

if x is not None and isinstance(x, (int, float)):
     return x**2
else:
     print "you have not entered x"

由于None不是int也不是float,您也可以省略第一个条件并写一下:

if isinstance(x, (int, float)):
     ...

答案 4 :(得分:1)

如果您可以识别所有输入必须兼容的单一类型,那么您可以转换它并处理异常:

def square(x=None):
    try:
        return float(x)**2
    except TypeError:
        print "You did not enter a real number"
        return None # Explicit is better than implicit

这有一些优点。

  • 它强制执行用户发送的任何内容与float兼容。这可以是任何数字,包含数字('5.0')的字符串,或其他任何可以转换为float的字符串。 (float实例未更改。)
  • 很简单。你的方法中没有奇怪的魔法。你不打破鸭子打字。您只需执行您的要求即可使工作正常。
  • 它不容易受到实际检查类型所涉及的问题的影响。您的来电者可以告诉您他们的自定义类型如何转换为float。 Python提供__float__魔术方法,因此如果您的用户具有异国情调并需要使用您的功能,他们就不会沉没。
  • 这是惯用的。有经验的Python程序员会期待这种代码;它遵循的是更容易请求宽恕而非许可"原理

旁边(可能):

如果None是无效值,请不要将其设为默认值。只需强制调用者提供输入:

def square(x):
    try:
        return float(x)**2
    except TypeError:
        print "You did not enter a real number"
        return None

答案 5 :(得分:0)

你可以在这里处理异常。制作这样的代码

def square(x):
    if not x:
        print "you have not entered x"
    else:
        try:
            int(y)=x**2
            return y
        except TypeError:
            pass


list=[1, 3, 0 ,9]
output=[]