问题
你明白了吧不是0(也不是0.0)在Python中返回True。可以通过简单的测试来看:
a = not 0
print(a)
Result: True
因此,解释了该问题。这一行:
if not x:
必须改为别的东西
解决方案
有几种方法可以解决这个问题。我只是从我认为是最好的解决方案列出到最后可能的解决方案:
>处理所有可能的有效情况。
因为平方根应该自然地期望一个数字输入,排除复数,并且应该返回一个错误,否则我认为最好的解决方案是使用if not isinstance(x,numbers.Number)或isinstance(x,numbers.Complex)来评估:
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)
numbers.Number是一个抽象类,用于检查参数x是否为一个数字(对于指出这一点而言为Copperfield)。
class numbers.Number
The root of the numeric hierarchy. If you just want to check if an
argument x is a number, without caring what kind, use isinstance(x,
Number).
但是,您不希望输入是复数。所以,只要忽略它使用或者isinstance(x,numbers.Complex)
This way, you write the definition of square exactly the way you
want it. This solution, I think, is the best solution by the virtue of
its comprehensiveness.
>只处理要处理的数据类型。
如果你有一个有效的inpug数据类型的列表,你也可以放置你想要处理的那些特定的数据类型。也就是说,您不想处理除了您指定的数据类型之外的数据类型的情况。例子:
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
You may change/extend the condition above easily for different data
types that you want to include or to excluded – according to your
need. This solution, I think, is the second best by the virtue of its
customization for its validity checking.
(上面的代码是以更为Pythonical的方式完成的,如cat所示)
>不处理不可能的情况:你知道用户不会作为输入。
如果你知道 – 不是第二个解决方案中要处理的数据类型,而是用户不会放置的数据类型,那么你可以更松散地考虑它,那么你可以像这样做更宽松的条件检查:
if not isinstance(x, numbers.Number): # this is ok, because the user would not put up complex number
This solution, I think, is the third best by the virtue of being one
of the simplest yet powerful checking.
此解决方案的唯一缺点是您不处理复杂类型。因此,只能由于用户不具有复数作为输入的事实才能实现。
>仅处理可能导致错误的已知可能输入的输入错误。
例如,如果您知道x始终为int或None – 因此唯一可能的输入错误为None – 那么我们可以简单地写入逻辑,以避免y仅在x为无时被评估:
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)
This solution has the virtue of being the simplest.
…但是如果您不知道用户输入的内容,最危险的被使用。否则,这个解决方案很好,也是最简单的。
您的解决方案,我认为或多或少属于这一类。您知道用户将会输入什么输入,用户不会输入什么。因此,使用此解决方案或您自己的解决方案:
if not x and not str(x).isdigit():
很好,除了示例解决方案更简单
鉴于您的情况,您可以使用上述任何解决方案获取:
[1, 9, 0, 81]
(侧面注意:我试图将解决方案格式化为“规范解决方案”,以便阅读目的,这样,有同样问题的人以及将来访问此页面的人可能会更全面地找到解决方案,可读)