“else” 在这里递归中是多余的吗?

huangapple go评论68阅读模式
英文:

Why is "else" redundant here in recursion?

问题

"else" here is redundant and not needed

def print_n(s, n):
    if n <= 0:
        return
    else:
        print(s)
        print_n(s, n-1)
    print_n("spam", 5)
英文:

Learning python, I got a question why "else" here is redundant and not needed

def print_n(s, n):
    if n &lt;= 0:
        return
**else:**
    print(s)
    print_n(s, n-1)
print_n(&quot;spam&quot;, 5)

答案1

得分: 0

You can remove the else because the if terminates with a return.

def print_n(s, n):
    if n <= 0:
        return
    print(s)
    print_n(s, n-1)

print_n("spam", 5)

I'm not sure that qualifies as redundant because some would like the else to be explicit, not implied. In this case its straightforward, but in the case of a more complicated if clause where the return isn't obvious (maybe there is a loop inside the if), one would like the else to be there.

英文:

You can remove the else because the if terminates with a return.

def print_n(s, n):
    if n &lt;= 0:
        return
    print(s)
    print_n(s, n-1)

print_n(&quot;spam&quot;, 5)

I'm not sure that qualifies as redundant because some would like the else to be explicit, not implied. In this case its straightforward, but in the case of a more complicated if clause where the return isn't obvious (maybe there is a loop inside the if), one would like the else to be there.

huangapple
  • 本文由 发表于 2023年5月7日 05:15:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76191175.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定