英文:
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 <= 0:
return
**else:**
print(s)
print_n(s, n-1)
print_n("spam", 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 <= 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论