python - python函数条件返回
问题描述
使用条件返回时,如果您尝试从函数返回多个值,则函数的行为与实际返回值有关。
def test_function(x,y, diagnostic:bool=False):
w = x*y
z = []
if diagnostic:
z = [w,w*2]
return z, w if diagnostic else w
print(test_function(3,4)) # output tuple ([],12)
# lets switch order of the return from z,w to w,z
def test_function(x,y, diagnostic:bool=False):
w = x*y
z = []
if diagnostic:
z = [w,w*2]
return w,z if diagnostic else w
print(test_function(3,4)) # output tuple (12,12)
# lets try retun the diagnostic value itself to see what function things is happening
def test_function(x,y, diagnostic:bool=False):
w = x*y
z = []
if diagnostic:
z = [w,w*2]
return diagnostic if diagnostic else w
print(test_function(3,4)) # returns 12, so diagnostic is retuning false
# rewrite conditional to "if not"
def test_function(x,y, diagnostic:bool=False):
w = x*y
z = []
if diagnostic:
z = [w,w*2]
return w if not diagnostic else w,z
print(test_function(3,4)) # returns (12, [])
解决方案
问题是运算符优先级:,
优先级低于... if ... else ...
,所以你实际写的是 like return z, (w if diagnostic else w)
,或者在第二个函数中,它是 like return w, (z if diagnostic else w)
。
对此的提示是,diagnostic
但False
您仍在返回一对值。
对于你想要的行为,你应该写return (z, w) if diagnostic else w
. 请注意,此处的括号不需要使其成为元组 - 无论哪种方式,它都是一个元组 - 括号用于指定优先级。
推荐阅读
- cloud-foundry - Cloudfoundry 重载终端信号
- javascript - Apollo GraphQL, is there a way to manipulate the data that is being written to the cache during querying?
- python - Creating a matrix from the data inside the csv
- java - 从目录路径创建 IJavaProject
- excel - VBA - 将范围的内容保存到文件中
- kubernetes - Kubernetes Istio 入口网关总是以 503 响应
- wordpress - Wordpress website hacked and .htaccess file is creating automatically with strange code
- javascript - Changing Image position when scrolling page
- html - 在悬停时使背景变暗
- c# - 指定的可执行文件不是此 OS 平台的有效应用程序。