从if语句中访问函数的值

时间:2016-05-20 09:31:37

标签: python syntax

是否可以缩短语法并从if语句访问函数的值而不显式声明返回值?例如,这样写:

if some_func():
    print('Somehow got the value of some_func()')

而不是:

x = some_func()
if x:
    print(x)

3 个答案:

答案 0 :(得分:0)

以下是如何做到的:

n

但它实际上并没有使你的代码更好,因为循环的存在是误导。坚持你所拥有的。更短的代码并不总是更好。

答案 1 :(得分:0)

是,

有可能这样做。

<强>例如

 def isEven(no):
     return not( no % 2)

 iN = 2
 if isEven(iN):
     print str(iN) + " is even"
  else:
     print str(iN) + " is odd"

当评估上述if语句时,它会查找isEven()的真值。在python中,以下值的真值为false: - [],{},空集,0,False,无(可能我可能会遗漏几个)。否则,其他值的真值为真。

答案 2 :(得分:0)

是的,你可以。函数返回的值用于if评估:

>>> def f():
...     return 1
... 
>>> if f()==1:
...    print('hey')
... 
hey