編寫一個 Python 程序,使用 For 循環、While 循環、函數和遞歸來查找一個數的階乘。Python 階乘用符號(!).數字的 Python 階乘是小於或等於該數字的所有數字的乘積&大於 0。n!= n (n-1) (n -2) ……。 1.
在這個 Python 數字階乘程序中,我們使用了內置的數學函數,稱為階乘。
import math
number = int(input(" Please enter any Number : "))
fact = math.factorial(number)
print("The fact of %d = %d" %(number, fact))
Python 數學階乘函數輸出
Please enter any Number : 5
The fact of 4 = 120
這個用於數字階乘的 python 程序允許用戶輸入任何整數值。使用此值,它使用 For 循環查找一個數的因數。
number = int(input(" Please enter any Number to find factorial : "))
fact = 1
for i in range(1, number + 1):
fact = fact * i
print("The factorial of %d = %d" %(number, fact))
用戶在上述 python 程序中輸入的整數示例為 4。請參考數學函數、階乘、 For Loop 、 While Loop 、Python 中的函數。
Python 階乘程序第一次迭代
i = 1,Fact = 1,number = 5
事實=事實 I;
事實= 1 1 = 1
第二次迭代
i = 2,Fact = 1,Number = 5
Fact = 1 * 2 = 2
第三次迭代
i = 3,事實= 2,數= 5
事實= 2 * 3 = 6
第四次迭代
i = 4,事實= 6,數= 5
事實= 6 * 4 = 24
接下來,我變成了 5。因此,對於循環終止。
在這個 python 階乘程序中,我們剛剛用 While 循環替換了 for 循環
number = int(input(" Please enter any Number to find factorial : "))
fact = 1
i = 1
while(i <= number):
fact = fact * i
i = i + 1
print("The factorial of %d = %d" %(number, fact))
Please enter any Number to find factorial : 8
The factorial of 8 = 40320
產出 2
Please enter any Number to find factorial : 9
The factorial of 9 = 362880
這個程序和第一個例子一樣。然而,我們使用函數 來分離邏輯
def factorial(num):
fact = 1
for i in range(1, num + 1):
fact = fact * i
return fact
number = int(input(" Please enter any Number to find factorial : "))
facto = factorial(number)
print("The factorial of %d = %d" %(number, facto))
Please enter any Number to find factorial : 5
The factorial of 5 = 120
產出 2
Please enter any Number to find factorial : 6
The factorial of 7 = 720
這個 Python 程序將用戶輸入的值傳遞給函數。在這個函數中,這個 Python 程序遞歸地找到一個數的階乘。
def factFind(num):
if((num == 0) or (num == 1)):
return 1
else:
return num * factFind(num - 1)
number = int(input(" Please enter any Num : "))
fact = factFind(number)
print("The fact of %d = %d" %(number, fact))
Please enter any Num : 6
The fact of 6 = 720
輸出 2
Please enter any Num : 4
The fact of 4 = 24
在這個 python 階乘程序的用戶定義函數中, If Else 語句檢查數字是等於 0 還是等於 1。如果條件為真,則函數返回 1。如果條件為假,函數遞歸返回 Num * (Num -1)。
用戶輸入值= 6。
fac = num fact find(num-1);
= 6 事實查找(5)
= 6 5 事實查找(4)
= 6 5 4 事實查找(3)
= 6 5 4 3 事實查找(2)
= 6 5 4 3 2 事實查找(1)
= 6 5 4 3 2
原創文章,作者:Q8R7B,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/127021.html