V tem programu se boste naučili poiskati faktorje številke z uporabo rekurzivne funkcije.
Če želite razumeti ta primer, morate poznati naslednje programske teme Python:
- Izjava Python, če … drugače
- Python funkcije
- Python rekurzija
Faktor na število je zmnožek vseh celih števil od 1 do tega števila.
Na primer, faktorijel 6 je 1*2*3*4*5*6 = 720
. Faktorijev ni določen za negativna števila in faktorja nič je ena, 0! = 1.
Izvorna koda
# Factorial of a number using recursion def recur_factorial(n): if n == 1: return n else: return n*recur_factorial(n-1) num = 7 # check if the number is negative if num < 0: print("Sorry, factorial does not exist for negative numbers") elif num == 0: print("The factorial of 0 is 1") else: print("The factorial of", num, "is", recur_factorial(num))
Izhod
Faktor 7 je 5040
Opomba: Če želite poiskati faktorijel druge številke, spremenite vrednost num
.
Tu je številka shranjena v num
. Število se posreduje recur_factorial()
funkciji za izračun faktorja števila.