如果自变量的结果满足条件,如何立即返回结果而不必重述自变量 [英] if result of argument satisfies a condition, how to return result immediately without having to restate the argument
本文介绍了如果自变量的结果满足条件,如何立即返回结果而不必重述自变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何返回满足条件的参数结果而不必在return函数中重写参数.
how to return a result of an argument that satisfies a condition without having to rewrite the argument in the return function.
例如(长方法)
if a+b > c:
return a+b
像这样的语法是否较短?
is there a shorter syntax in the likes of-
if a+b > c
return ans
(在这种情况下为 ans == a + b
)
通常,该参数比a + b复杂得多,因此省去了重新输入整个参数的麻烦
usually, the argument is much more complex than just a + b so it would save a lot of trouble retyping the entire argument
推荐答案
您可以使用海象"运算符:
You can use the "walrus" operator:
if (ans := a + b) > c:
return ans
在最新的Python版本(3.8+)中.
in the latest Python version (3.8+).
这篇关于如果自变量的结果满足条件,如何立即返回结果而不必重述自变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文