While循环中的递归函数(Python)

时间:2015-11-15 04:04:49

标签: python recursion

所以我正在学习Python中的递归,我有一些代码可以找到用户输入数字的阶乘。

def recursion(x):
    if x == 1:
        return 1
    else:
        return(x * recursion(x - 1))

num = int(input("Enter a non-negative integer: "))
if num >= 1:
    print("The factorial of", num, "is", recursion(num))

此代码工作正常。也就是说,它会询问指定的问题,允许用户输入,并找到数字的阶乘。所以我要做的是将该递归函数放在While循环中,以便在程序打印所提交数字的阶乘后,它会询问用户是否想要输入另一个数字。

loop = 1
while loop == 1:

def recursion(x):
    if x == 1:
        return 1
    else:
        return(x * recursion(x - 1))

num = int(input("Enter a non-negative integer: "))
if num >= 1:
    print("The factorial of", num, "is", recursion(num))
    print()
    answer = input(print("Would you like to find the factorial of another non-negative integer? Y/N: "))
    if answer == "Y":
        loop = 1
    else:
        loop = 0

我对此代码的问题是它会询问用户输入数字,找到阶乘,并询问问题“你想找到另一个非负整数的阶乘吗?Y / N :“但是当我在IDLE中运行它时,上述问题之后的行说”无“。

Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:27:37) 
[MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
Enter a non-negative integer: 6
The factorial of 6 is 720
Would you like to find the factorial of another non-negative integer? Y/N: 
NoneY
Enter a non-negative integer: 4
The factorial of 4 is 24
Would you like to find the factorial of another non-negative integer? Y/N: 
NoneN
>>> 

我浏览了Python documentation (section 4.6),并提到解释器通常会抑制“无”。

  1. 为什么,当我在IDLE中运行它时,它是否在循环控制问题之后显示“无”?
  2. 有没有办法省略“无”并仍然使用print()?

2 个答案:

答案 0 :(得分:3)

您看到None的原因是因为print内有input

input(print("Would you like to find the factorial of another non-negative integer? Y/N: "))

删除print

input("Would you like to find the factorial of another non-negative integer? Y/N: ")

答案 1 :(得分:1)

这一行:

answer = input(print("Would you like to find the factorial of another non-negative integer? Y/N: "))

print会返回None,因此您将None输入到您的阶乘函数中,然后将None作为答案。

应该是:

answer = input("Would you like to find the factorial of another non-negative integer? Y/N: ")