python 递归函数与循环的区别_关于递归:While循环中的递归函数(Python)

因此,我正在学习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

我在这段代码中遇到的问题是,它将要求用户输入一个输入数字,找到阶乘,然后问"是否要查找另一个非负整数的阶乘?是/否:"问题,但是当我在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文档(第4.6节),其中提到解释器通常禁止显示" None"。

为什么当我在IDLE中运行此代码时,在循环控制问题之后它是否显示" None"?

有没有办法忽略"无"而仍然使用print()?

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

之所以看到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:")

做到了。 谢谢idjaw!

这行:

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

谢谢戴尔! 该程序不再显示"无"。 现在,我只需要弄清楚如何在程序中进行一些错误检查,Itll就可以完成了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值