Home > Back-end >  Why does my recursion program to find the factorial of a base number not work?
Why does my recursion program to find the factorial of a base number not work?

Time:10-25

My program to calculate the Factorial of a base number recursively and starting over on the user's command doesn't work, it shows errors:

Result = 0

def factorial(Base):
    if Base == 0 and Base == 1:      
        Result = 1                                   
    else:
        Result = Base * factorial(Base - 1) 
    print(f"Factorial of {Base} is = {Result}")                             

i: bool = True
while True:
   Base: int = int(input("Enter a base number: "))
   factorial(Base)
   offf: str = input("Enter 'off' to terminate calculations: ")
   if offf == "off":
    i = False
    print("Calculations Terminated")

CodePudding user response:

There are several issues in your code. Let's correct them

#no need to set a global variable
#Result = 0

def factorial(Base):
    #the if here is wrong, a number cannot be 0 AND 1 at the same time
    #if Base == 0 and Base == 1:
    if Base == 0 or Base == 1: #could also be just Base <= 1      
        Result = 1                                   
    else:
        Result = Base * factorial(Base - 1)
    #do you really want to print all the intermediate results? 
    print(f"Factorial of {Base} is = {Result}")
    return Result                             

i: bool = True
#while True will run forever unless you set a break
#while True:
while i:
    Base: int = int(input("Enter a base number: "))
    #now factorial returns a number, but we need to use it 
    #factorial(Base)
    print(f"Factorial of {Base} is = {factorial(Base)}")

    offf: str = input("Enter 'off' to terminate calculations: ")
    if offf == "off":
        i = False
        print("Calculations Terminated")

CodePudding user response:

You are checking for a condition that can never be true, Change the "and" to an "or" and it should work.

if Base == 0 or Base == 1:

Edit: Answer to comment: it doesn't look like the author wants to return a value he just wants to print the value to see that it works. If the function should return a value, then its easy to add.

Also instead of setting result to 1 for the base case, it should return 1 since it is a recursive function.

def factorial(Base):
    if Base == 0 or Base == 1:
        return 1
    else:
        Result = Base * factorial(Base - 1)
    return Result
print(factorial(5))

CodePudding user response:

Try this way:

#!/usr/bin/python
    num=8
    factorial=1
    
    k=1
    while(k<=num):
        factorial = k*factorial
        k=k 1
    print(factorial)

in this case the program calculate the factorial of 8

  • Related