In: Computer Science
Create the function fact that had a positive integer argument and returns its factorial . Recall that factorial (n) = 1*2*3***n. For example factorial (4)=1*2*3*4=24, (python)
Factorial is the product of all positive integer which is less than given number is known as factorial of that number for example we can say 24 is the factorial of number 4.
24 = 1*2*3*4;
here i wrote the code in python 3. and after this // i will comment about line and also comment will in green color and code in black color :
def fact(val): //
this is the function declartion with parameter which we want to
pass so here i am passing val parameter to this
function.
total=1 // here i take total variable in which i will
store factorial value.
for i in range(1,val+1):
// for loop for factorial calculation
here i am taking range 1 to val+1 (where val is the value which we
give to calculate factorial ) because 1 will be starting point of
for loop but if we give only val as stop point so python will take
val - 1 as a stop point so i give val + 1.
total=total *
i // here our
loop will run at val times and it will calcutate
factorial
return
total // now function will return factorial value which
is we stored in total.
val = int(input("enter a number"))
// here we are taking user input and
storing to val. and here also i added int so it will take only
integer value.
print("(",val,") =",end=" ")
// from this line it will print ( val
) =
for i in range(1,val): // in this loop we will get output of sequence and
multiply symbol until value-1 which we will enter.
print(i,"*",end=" "),
print(val," = ",fact(val)) // now finally we call the function by fact(val)
and before this we will print number which we will enter because
above for loop print till val -1 and then after function call
function give factorial and which will print.