Python basics: How to check if a function returns mutiple values?
我知道一些基本的东西…;-p但是检查函数是否返回一些值的最好方法是什么?
1 2 3 4 5 6 7 | 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 |
如果您的意思是不能预测某个函数的返回值的数量,那么
1 | i, j = hillupillu() |
如果函数不返回两个值,将引发
1 2 3 4 | try: i, j = hillupillu() except ValueError: print("Hey, I was expecting two values!") |
这遵循了常见的python成语"请求原谅,而不是许可"。如果
1 2 3 4 | 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 |
如果您想在返回值中检查
python中的函数总是返回单个值。尤其是它们可以返回一个元组。
如果不知道一个元组中有多少值,可以检查其长度:
1 2 3 | tuple_ = hillupillu() i = tuple_[0] if tuple_ else None j = tuple_[1] if len(tuple_) > 1 else None |
1 2 | if(i =="" or j ==""): //execute code |
沃德克应该是这样的,但是如果你给它一个
1 2 | if(i == None or j == None): //execute code |
希望有所帮助
从函数接收值后:
1 | i, j = hillupillu() |
您可以使用
1 | if i is None: ... |
您还可以测试值的真值:
1 | if i: ... |