的if-else-Return或只是如果 - 返回? [英] If-Else-Return or just if-Return?

查看:211
本文介绍了的if-else-Return或只是如果 - 返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个收益如果语句。从效率的角度来看,我应该使用

Suppose I have an if statement with a return. From the efficiency perspective, should I use

if(A > B):
    return A+1
return A-1

if(A > B):
    return A+1
else:
    return A-1

有人可以解释我的区别?是否有编译语言VS跨preTED之一的任何差别(例如C)(例如Python)的?

Can someone explain me the difference? Is there any difference in a compiled language (e.g. C) vs an interpreted one (e.g. Python)?

推荐答案

由于收益语句终止当前函数的执行,这两种形式是等价的(虽然第二个可以说是比第一个更可读)。

Since the return statement terminates the execution of the current function, the two forms are equivalent (although the second one is arguably more readable than the first).

这两种形式的效率相媲美,底层机器code的,如果如果条件为假反正进行跳转。

The efficiency of both forms is comparable, the underlying machine code has to perform a jump if the if condition is false anyway.

请注意Python支持一种语法,可以让你在你的情况下,仅使用一个收益语句:

Note that Python supports a syntax that allows you to use only one return statement in your case:

return A+1 if A > B else A-1

这篇关于的if-else-Return或只是如果 - 返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆