在下面的代码中,即使n == 0,也执行“结果= n *递归”。如果执行语句,则不应忽略else语句。换句话说,两个代码为什么给出相同的输出?
我的理解是,在第一个代码中,一旦n == 0,如果满足条件,则将不会执行其他语句。因此,在第一个代码的输出中不应有“ returning 1”开头的打印。
def factorial(n):
space = ' ' * (4 * n)
print(space, 'factorial', n)
if n == 0:
print(space, 'returning 1')
return 1
else:
recurse = factorial(n-1)
result = n * recurse
print(space, 'returning', result)
return result
def factorial(n):
space = ' ' * (4 * n)
print(space, 'factorial', n)
if n == 0:
print(space, 'returning 1')
return 1
else:
recurse = factorial(n-1)
result = n * recurse
print(space, 'returning', result)
return result
factorial (4)
Both the codes gives the same result:
factorial 4
factorial 3
factorial 2
factorial 1
factorial 0
returning 1
returning 1
returning 2
returning 6
returning 24
答案 0 :(得分:3)
这是因为所讨论的行不在if-else语句的范围内,请参见下面的代码中的注释:
def factorial(n):
space = ' ' * (4 * n)
print(space, 'factorial', n)
if n == 0:
print(space, 'returning 1')
return 1
else:
recurse = factorial(n-1)
result = n * recurse # ****THIS IS OUTSIDE IF CLAUSE****
print(space, 'returning', result)
return result
如果要让result = n * recurse
在else语句中,请使用与recurse = factorial(n-1)
相同的缩进:
def factorial(n):
space = ' ' * (4 * n)
print(space, 'factorial', n)
if n == 0:
print(space, 'returning 1')
return 1
else:
recurse = factorial(n-1)
result = n * recurse # ****THIS IS INSIDE IF-ELSE CLAUSE****
print(space, 'returning', result)
return result