[英]Recursive Function inside While loop (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”。
之所以看到“ 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: ")
這行:
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: ")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.