【发布时间】: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