-2
def factorial(n):
    if(n == 1):
        fact = 1
        return fact
    else:
        fact = a * factorial(n - 1)
        return fact
    a = int(input("Enter a number to find its factorial: ")
    if (a > 0):
        print("The factorial of", a, "is:", fact)
    else:
        print("Enter a positive value to find its factorial")

In the above code it tells me that - NameError name 'fact' is not defined .

  • 2
    move this `fact = 1` to outside `if` block – deadshot Sep 23 '20 at 05:06
  • @deadshot why???? they return in both branches of `if`. I'm pretty sure OP looking for some other help. – Alexei Levenkov Sep 23 '20 at 05:11
  • If you want the correct logic: refer [this](https://stackoverflow.com/questions/5136447/function-for-factorial-in-python) post. And also, I would recommend you to read the basic python syntax and rules, because your code have more than 1 logical and syntactical errors; For eg. both fact and a variable are used before assignment. – Sadiq Raza Sep 23 '20 at 05:16
  • Please [edit] your question to copy-paste the *full* and *complete* error output. And add a comment on the line where you get the error. – Some programmer dude Sep 23 '20 at 05:17
  • General remark, Python should tell you the line of the error, should be helpful to include this information. Also: Are you sure the Not Defined Error is for `fact`? From the code it should be for `a`, since it gets used in fact = a*... without ever being defined. Also you are missing a ')' in the a = int.... line which btw will never be executed because it's after an if/else return statement. – Bernhard Sep 23 '20 at 05:20
  • The error you claim to get doesn't match the code you show. You need to make sure that we have the full and complete error output, ***and*** a [mcve] which can be used to replicate the error. – Some programmer dude Sep 23 '20 at 05:39

2 Answers2

1

Lines starting from a = int... should be outside your function. Once that is done all you need is to add fact = factorial(a).

aragaer
  • 17,238
  • 6
  • 47
  • 49
-2

Find the correct logic below.

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))
Iceman
  • 157
  • 1
  • 9