[英]Unwanted None at the end of the Recursion in Python
when I try to print the all the natural numbers from 1 to n using recursion I'm getting None at the end of the result My code当我尝试使用递归打印从 1 到 n 的所有自然数时,我在结果末尾得到 None 我的代码
def num_1_to_n(n):
if n==1:
return n
print(n)
print(num_1_to_n(n-1))
n=int(input(enter the n value))
num_1_to_n(n)
I wanted to get我想得到
4
4
3
2
1
but I get但我明白了
4
4
3
2
1
None
None
None
Can anyone please tell me the reason behind the printing of None
after 1谁能告诉我在 1 之后打印
None
的原因
Recursion often occurs problems like this, so use for loops:递归经常会出现这样的问题,所以使用for循环:
n = int(input("Enter the n value"))
for i in range(n, 1, -1):
print(i)
print(1) # for the loop to not stop at 2
Or, shorter:或者,更短:
n = int(input("Enter the n value"))
for i in range(n, 0, -1):
print(i)
try this code试试这个代码
def num_1_to_n(n):
if n==1:
print(1)
return n
print(n)
num_1_to_n(n-1)
n=int(input("enter the n value"))
num_1_to_n(n)
Output: Output:
enter the n value4
4
3
2
1
you gate those none because of print(num_1_to_n(n-1)) this print因为 print(num_1_to_n(n-1)) 这个打印,你把那些没有门
In your code在您的代码中
def num_1_to_n(n):
if n==1:
return n
print(n)
print(num_1_to_n(n-1))
the statement print(num_1_to_n(n-1))
prints the return value of the function call num_1_to_n(n-1)
.语句
print(num_1_to_n(n-1))
打印 function 调用num_1_to_n(n-1)
的返回值。 Your function returns 1
in case of n == 1
and None
otherwise, since Python implicitly returns None
when it reaches the end of a function body during execution (emphasis mine):您的 function 在
n == 1
的情况下返回1
,否则返回None
,因为Python 在到达 ZC1C425268E68385D1AB5074C17A94F1Z4 主体的末尾时隐式返回None
(执行期间):
The return statement returns with a value from a function.
return 语句返回来自 function 的值。 return without an expression argument returns None.
没有表达式参数的返回返回无。 Falling off the end of a function also returns None .
从 function 的末端掉落也返回 None 。
So you will see three None
for the three calls where n != 1
, when you start at 4
.因此,当您从
4
开始时,您将看到三个None
用于n != 1
的三个调用。
Also you can try it this way:你也可以这样尝试:
def num_1_to_n(n):
if n > 1:
print(n)
num_1_to_n(n-1)
else:
print(1)
n=int(input('enter the n value: '))
num_1_to_n(n)
It is printing None
because you of print(num_1_to_n(n-1))
when you only need to call the function like num_1_to_n(n-1)
.当您只需要像
num_1_to_n(n-1)
一样调用 function 时,它正在打印None
因为您是print(num_1_to_n(n-1))
) 。
Final Code:最终代码:
def num_1_to_n(n):
if n==1:
print(1)
return n
print(n)
num_1_to_n(n-1)
n=int(input("enter the n value"))
num_1_to_n(n)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.