# Python Function Recursion 2

Question:2
Python script to calculate factorial of a no (Method:2)
Sol:

```def fact(n):
if(n<0):
return(-1)
if(n==0):
return(1)
else:
return(n*fact(n-1))

#function calling
while True:
a=int(input("Enter any no "))
b=fact(a)
if(b==-1):
print("-ve nos not allowed")
else:
print("Fact = ",b)
ch=input("Like to cont ")
if(ch=='y' or ch=='Y'):
continue
else:
break```

Output:

Enter any no 5
Fact = 120
Like to cont y
Enter any no 6
Fact = 720
Like to cont y
Enter any no 4
Fact = 24
Like to cont y
Enter any no 3
Fact = 6
Like to cont n
>>>

Question:3
Python script to calculate the sum of first “n” numbers
Sol:

```def sum(n):
s=0
if(n==0):
return(s)
else:
return(n+sum(n-1))

#function calling

while True:
a=int(input("Enter the limit "))
s=sum(a)
print("Sum = ",s)
ch=input("Like to cont .... (y/n) ")
if(ch=='y' or ch=='Y'):
continue
else:
break```

Output:

Enter the limit 5
Sum = 15
Like to cont …. (y/n) y
Enter the limit 10
Sum = 55
Like to cont …. (y/n) y
Enter the limit 20
Sum = 210
Like to cont …. (y/n) n
>>>

Question:4
Python script to calculate product of first “n” numbers
Sol:

```def prod(n):
p=1
if(n==0):
return(p)
else:
return(n*prod(n-1))

#function calling

while True:
a=int(input("Enter the limit "))
p=prod(a)
print("Prod = ",p)
ch=input("Like to cont .... (y/n) ")
if(ch=='y' or ch=='Y'):
continue
else:
break```

Output:

Enter the limit 3
Prod = 6
Like to cont …. (y/n) y
Enter the limit 5
Prod = 120
Like to cont …. (y/n) y
Enter the limit 6
Prod = 720
Like to cont …. (y/n) y
Enter the limit 4
Prod = 24
Like to cont …. (y/n) n
>>>

Important Pages