【问题标题】:Can print function catch None return value and not print it?打印函数可以捕获 None 返回值而不打印它吗?
【发布时间】:2016-12-08 04:14:37
【问题描述】:

我是新手,正在学习 Python。避免在下面的代码中打印 None 的最佳方法是什么?我注释掉了一个错误。

我知道为什么要打印 None。我本来希望该函数有 2 种返回类型,但根据 S.Lott 对 Why should functions always return the same type? 的回复,显然这对于​​代码的可维护性来说是不好的做法。此外,unutbu 在同一篇文章中的回答是,当您在期望某种类型的函数中调用该函数时会弹出错误 - fun1(fun2(arg))。我不想像 S.Lott 建议的那样引发运行时错误。有没有办法打印捕获 None 值而不打印它?

def smaller_root(a,b,c):
    """
    akes an input the numbers a,b and c returns the smaller solution to this 
    equation if one exists. If the equation has no real solution, print 
    the message, "Error: No Real Solution " and simply return.
    """
    discriminant = b**2-4*a*c

    if discriminant == 0:
        return  -b/(2*a)
    elif discriminant > 0:
        return (-b-discriminant**0.5)/(2*a) #just need smaller solution
    else:
        print("Error: No Real Solution")
        #raise Exception("Error: No Real Solution")
        #no return statement as there is no use for it. 
        #Python will implicitly return None

【问题讨论】:

  • 返回None,调用函数时避免打印。如果您提出异常 None 将不会被返回,但我认为异常不能很好地表明没有找到解决方案。
  • @MarounMaroun 相反,这是一个很好的例外情况。最重要的是:“错误不应该默默地过去。”
  • @Rhymoid 这不是错误;只是没有解决办法。
  • @MarounMaroun 如果这是程序(其余部分)无法处理的情况,则应将其建模为错误。
  • @Rhymoid 我认为这是一个设计问题,只要你保持一致就可以了。

标签: python python-2.7 python-3.x types


【解决方案1】:

你的函数做一个,而且只有一个,事情。所以,在你的情况下,它应该根据一些变量找到smaller_root

你的函数的返回值应该是根。在您的情况下,它可能返回None,这表明该解决方案没有根。

然而,你试图让函数做不止一件的事情,也就是说,你试图让函数返回一个值(根)并在没有根的情况下打印一条消息找到了。

你应该只为你的函数选择一个功能:它将EITHER打印出结果(即打印根或消息)返回结果。

功能之外的所有其他逻辑都将超出功能的范围,例如:

def smaller_root(a,b,c):
    """
    akes an input the numbers a,b and c returns the smaller solution to this 
    equation if one exists. If the equation has no real solution, print 
    the message, "Error: No Real Solution " and simply return.
    """
    discriminant = b**2-4*a*c

    if discriminant == 0:
        return  -b/(2*a)
    elif discriminant > 0:
        return (-b-discriminant**0.5)/(2*a) #just need smaller solution
    else:
        return None

result = smaller_root(some_a, some_b, some_c)
if (result is None):
    print("Error: No Real Solution")

【讨论】:

    猜你喜欢
    • 2015-11-14
    • 2021-12-30
    • 2013-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-17
    • 1970-01-01
    相关资源
    最近更新 更多