-3

I am completely new to python, and I am having trouble with returning the factorial variable. I am trying to create a recursive function. I keep getting errors on line 12, 9, and 7 with the words "local variable 'factorial' referenced before assignment". Any help is appreciated.

global userinput
userinput = input('What integer would you like to to find a total factorial     for?')
def recursion(counter):
  if counter < 3:
     factorial = 1
  if counter <= userinput:
     factorial = factorial * counter
     increase = counter + 2
     recursion(increase)
  else:
     return factorial
efactorial = recursion(2)
ofactorial = recursion(1)
tfactorial = efactorial + ofactorial
Brantley
  • 69
  • 1
  • 3
  • This part: `factorial = factorial * counter` references `factorial` (on the right hand side), but it has not been set to a number yet. – James Mar 03 '17 at 02:06
  • By the way, math module has a factorial function – Taku Mar 03 '17 at 02:07

2 Answers2

1

If the counter in the recusion function is beyond 3, then the factorial won't be assigned. Thus, the expression in the second if will trigger an unassignment error. Try this:

def recursion(counter):
    if counter < 3:
        factorial = 1
    else:
        factorial = xx # Any value you want
    ...
Hou Lu
  • 3,012
  • 2
  • 16
  • 23
0

IMMEDIATE PROBLEM

Several others have already pointed out that you're using a local variable that you haven't defined (given a value) if the input argument is >= 3. Immediately after that, you employ the recursion step, but then ignore the return value:

 increase = counter + 2
 recursion(increase)

recursion returns a value, but you fail to keep it anywhere. Thus, you lose the result entirely.

TECHNIQUE

In general, you use recursion to solve a simpler problem, and then incorporate the result of that simpler problem in your solution. With the code you've given, it might look something like this:

factorial = counter * recursion(counter + 2)
return factorial

Or simply

return counter * recursion(counter + 2)

FUNCTIONAL PROBLEM

I have no idea why you separate odd and even numbers. The result you get is not what mathematicians call "factorial".

COMMON APPROACH

The actual factorial function is a common programming exercise. The canonical algorithm is to start with the desired number and work backward to 1. This is in research you were supposed to do before you posted your question; obviously, you have a a different problem, and you need a solution for your code.

Prune
  • 76,765
  • 14
  • 60
  • 81