Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从if语句访问函数值_Python_Syntax - Fatal编程技术网

Python 从if语句访问函数值

Python 从if语句访问函数值,python,syntax,Python,Syntax,是否可以缩短语法并从if语句访问函数值,而不显式声明返回值?例如,这样写: if some_func(): print('Somehow got the value of some_func()') 而不是: x = some_func() if x: print(x) 以下是您如何做到这一点: def optional(x): if x: yield x for x in optional(some_func()): print(x) 但

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

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

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

以下是您如何做到这一点:

def optional(x):
    if x:
        yield x

for x in optional(some_func()):
    print(x)

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

以下是如何做到这一点:

def optional(x):
    if x:
        yield x

for x in optional(some_func()):
    print(x)
但是它实际上并不能使代码变得更好,因为循环的存在是误导性的。坚持你所拥有的。代码越短并不总是越好。

是的

这样做是可能的

例如

 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、None(可能是我缺少了更多)。否则,其他值的真值为真。

这样做是可能的

例如

 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、None(可能是我缺少了更多)。否则,其他值的真值为真。

可以。函数返回的值用于
if
求值:

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

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

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

你已经回答了你自己的问题是的,你可以使用它,它完全有效你可以,但你不应该,它只是在转移问题。你已经回答了你自己的问题是的,你可以使用它,它完全有效你可以,但你不应该,它只是在转移问题。确实,它不值得蜡烛。确实,这不值得一支蜡烛。