【问题标题】:Recursive Function inside While loop (Python)While循环内的递归函数(Python)
【发布时间】:2015-11-15 04:04:49
【问题描述】:

所以我正在学习 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 中运行它时,它会在循环控制问题之后显示“None”?
  2. 有没有办法省略“None”并仍然使用 print()?

【问题讨论】:

  • 请将函数recursion移出while循环。无需在循环中一遍又一遍地重新定义。

标签: python recursion


【解决方案1】:

您之所以看到None,是因为您的input 中有一个print

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: ")

【讨论】:

    【解决方案2】:

    这一行:

    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: ")
    

    【讨论】:

    • 感谢代尔!该程序不再显示“无”。现在我只需要弄清楚如何在程序中进行一些错误检查,它就完成了。
    猜你喜欢
    • 2016-03-19
    • 2023-02-22
    • 2018-08-15
    • 2018-03-15
    • 2013-08-12
    • 2021-02-27
    • 1970-01-01
    • 2011-05-07
    • 1970-01-01
    相关资源
    最近更新 更多