python语句前的条件

python语句前的条件,python,conditional-statements,Python,Conditional Statements,在Go中,可以在语句之前使用条件句: if num := 9; num < 0 所以我想这样使用它: if res, val = myfunc() TEST FOR res: do_something() 这在python中是不可能的。把它分成两行 res, val = myfunc() if res: do_something() 自Python 3.8以来,您可以使用: 我们将输出分配给一个元组out,并测试其第一项是否为True: def myfunc(val):

在Go中,可以在语句之前使用条件句:

if num := 9; num < 0 
所以我想这样使用它:

if res, val = myfunc() TEST FOR res:
  do_something()

这在python中是不可能的。把它分成两行

res, val = myfunc()
if res:
    do_something()

自Python 3.8以来,您可以使用:

我们将输出分配给一个元组
out
,并测试其第一项是否为
True

def myfunc(val):
  if val > 0:
    return [ True, val ]
  else:
    return [ False, val ]

if (out := myfunc(5))[0]:
    print(out)
else:
    print('That was False')
# [True, 5]


if (out := myfunc(-2))[0]:
    print(out)
else:
    print('That was False')
# That was False
遗憾的是,我们无法在运行时打开元组:

if ((res, val) := myfunc(-2))[0]:
    print(val)
else:
    print('That was False')

     File "<ipython-input-10-03724761d41a>", line 20
    if ((res, val) := myfunc(-2))[0]:
        ^
SyntaxError: cannot use named assignment with tuple
if((res,val):=myfunc(-2))[0]:
打印(val)
其他:
打印('这是错误的')
文件“”,第20行
如果((res,val):=myfunc(-2))[0]:
^
SyntaxError:无法对元组使用命名赋值

所以这似乎是不可能的。 我想在同一条语句上进行赋值和测试,就像在围棋中一样


关闭此操作。

是否需要在以后访问返回值?然后写在两行上。否则:
如果myfunc()[0]:
…为什么要使用单独的布尔值?您可以执行类似于
if(valid_condition)的操作:返回val;else:返回None
,然后测试
None
。是的,我希望能够为res分配res,val=myfunc(),并在同一行上测试res,并在if块中使用val
if ((res, val) := myfunc(-2))[0]:
    print(val)
else:
    print('That was False')

     File "<ipython-input-10-03724761d41a>", line 20
    if ((res, val) := myfunc(-2))[0]:
        ^
SyntaxError: cannot use named assignment with tuple