《Python基础:如何检查函数是否返回多个值?》

2024-09-27 02:19:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道的基本知识…;-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 

Tags: orand方法函数innonereturnif
3条回答

从函数接收值后:

i, j = hillupillu()

可以使用is运算符检查值是否为None

if i is None: ...

你也可以测试这个值的真值:

if i: ...

如果你的意思是你不能预测某个函数的返回值的数目,那么

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-子句中的None in (i, j)

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

相关问题 更多 >

    热门问题