如果/else语句(Python)返回外部
当您有以下代码时:
def func(a) -> Optional[S]
if len(a) == 2:
x = "bla bla bla"
else:
if a.state is True and len(a) == 3:
s = "hello world"
return s
注意:S是S的实例。
我有两个问题。请按顺序回答。
当您在外返回时,如果返回s ,则在下方 else> else 下方,则在何时执行返回?如果是false,将在内部的任何一个条件之后执行返回?
如果我这样做,它将有什么区别
def func(a) - >可选[S] 如果len(a)== 2: x =“ bla bla bla” 别的: 如果A.STATE为真,并且Len(a)== 3: S =“ Hello World” 返回s
When you have the following code:
def func(a) -> Optional[S]
if len(a) == 2:
x = "bla bla bla"
else:
if a.state is True and len(a) == 3:
s = "hello world"
return s
Note: s is an instance of S.
I have two questions. Please answer them in order.
when you have the
return s
outside the innerif
and right below the outerelse
, then after when would that return be executed? Will the return be executed after either of the conditions in the inner if is false?What difference will it make if I do this instead, where the return is just outside the inner if now.
def func(a) -> Optional[S] if len(a) == 2: x = "bla bla bla" else: if a.state is True and len(a) == 3: s = "hello world" return s
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
之后执行,就像在此处放置的任何其他语句一样。请注意,如果
条件为true,或者两种条件都是正确的,则您将获得错误,因为在这种情况下,您永远不会分配s
。返回
语句在else中移动:
如果条件为true,则将不会执行。在这种情况下,该函数将不会以返回
语句结束,因此默认情况下它将返回none
。这将避免在条件为真时尝试使用s
的错误,但是如果这两个条件都不是,则仍然会出现错误。避免该问题的方法是将返回
将最内向移动到:另外,我们通常将 else组合:如果 ,因此代码应为:
if/else
code is executed, just like any other statement placed there. Note that you'll get an error if theif
condition is true, or if neither condition is true, because in that case you never assigns
.return
statement inside theelse:
it won't be executed when theif
condition is true. IN that case the function will end with noreturn
statement, so it will returnNone
by default. This will avoid the error of trying to uses
when theif
condition is true, but it will still get an error if neither condition is true. The way to avoid that problem is to move thereturn
into the innermostif
:Also, we normally combine
else: if
intoelif
, so the code should be: