我知道一些基本的东西...;-P但是检查函数是否返回一些值的最好方法是什么?
def hillupillu():
a= None
b="lillestalle"
return a,b
if i and j in hillupillu(): #how can i check if i or j are empty? this is not doing it of course;-P
print i,j 发布于 2011-10-09 00:59:09
如果您的意思是不能预测某个函数的返回值的数量,那么
i, j = hillupillu()如果函数没有恰好返回两个值,将引发ValueError。您可以使用常用的try构造来捕获它:
try:
i, j = hillupillu()
except ValueError:
print("Hey, I was expecting two values!")这遵循了常见的Python成语“请求宽恕,而不是许可”。如果hillupillu本身可能会引发ValueError,则需要进行显式检查:
r = hillupillu()
if len(r) != 2: # maybe check whether it's a tuple as well with isinstance(r, tuple)
print("Hey, I was expecting two values!")
i, j = r如果您的意思是要检查返回值中的None,那么请检查if-clause中的None in (i, j)。
发布于 2011-10-09 01:10:12
Functions in Python always return a single value。特别是,它们可以返回一个元组。
如果你不知道一个元组中有多少个值,你可以检查它的长度:
tuple_ = hillupillu()
i = tuple_[0] if tuple_ else None
j = tuple_[1] if len(tuple_) > 1 else None发布于 2011-10-09 01:00:53
从函数接收到值后:
i, j = hillupillu()您可以使用is操作符检查某个值是否为None:
if i is None: ...您也可以只测试值的真值:
if i: ...https://stackoverflow.com/questions/7698329
复制相似问题