I am coding a function that generates the factorial of a number. As a reminder to all the factorial
of 3 is 3*2*1=6. Etc. I wrote a piece of code that works fine except for a particular if statement
that I had to add in especially for the case of 1, the factorial of which is 1. My code works fine
without the if statement that is created for the case of 1. The code runs fine if I enter any positive
number other than 1 as the argument for the function "factorial". I am expecting it to print the
string 1 to the console, but it doesn't. I will share my code now:
Code:
def factorial(x):
count = x
list_of_nums = []
while count > 0:
list_of_nums.append(count)
count -= 1
print list_of_nums
for i in xrange(len(list_of_nums)):
if len(list_of_nums) == 1:
print "1"
break
elif i == 0:
fact_of_nums = list_of_nums[i] * (list_of_nums[i] - 1)
elif i < (len(list_of_nums) - 1):
fact_of_nums = fact_of_nums * (list_of_nums[i] - 1)
print fact_of_nums
factorial(1)
ERROR:
Code:
Traceback (most recent call last):
File "/Users/Tom/Documents/Python/additionaltestingground.py", line 18, in <module>
factorial(1)
File "/Users/Tom/Documents/Python/additionaltestingground.py", line 16, in factorial
print fact_of_nums
UnboundLocalError: local variable 'fact_of_nums' referenced before assignment
[Finished in 0.0s with exit code 1]
If someone would help me figure out what's going wrong here I'd appreciate it highly. Thank you
for your time.