Here's the question you clicked on:
harsimran_hs4
hi guys in lec8 (6.00, 2011), function fact(n) if i modify it a little(2 different ways) i am getting error whereas i don`t think removing this statement should affect the code..please can you tell me my mistake(also little details about error). Here is the code: http://pastebin.com/FXpk8NqW
for recursive functions you need to have the option of having a recursive call *and* a base case in each definition. neither of your definitions have base cases like if n==1 or n==0: return 1 ^^^^^^ these are your base cases
can you explain a little more about base case.... and isn't the assert doing the same....and in the function fact(n) i have removed only if condition i.e if the number being negetive or less than 1 then it should return the same no.
You need to think a little more mechanically about each step: First of all, assert only limits the types of inputs allowed; it has nothing to do with a base case. The base case is what all possible inputs will tend to as n decreases on each recursive call. Since every recursive call is to n*fact(n - 1), this tells us that our input n is decreasing on each call. We will get *no final result* unless this terminates, which without a base case, it does not.
def fact1(n): assert n >= 0 #makes sure that input is positive and an integer return n*fact1(n-1) #calls back to fact1 with an input of one less problem: you have nothing in the code that tells it to terminate. There is no endpoint to this function; it will just call on fact(n-1) even after n gets negative. You need a base case to fix this.
def fact(n): assert n >= 0 if n > 1: return n*fact(n - 1) okay, this one is a little better, but you have in no way specified what happens after n==0 all we have are recursive calls to the function again, with no final output. Your only return statement involves another function, so you will get no numerical output.
it seems to me that you think that the assert operator will give you some return once we get to a point where the input is negative, but it will not. you need another return statement with the base case(s) is the moral of the story.
i appreciate your efforts to explain but i am little confused how about this code def fact(n): if n > 1: return n*fact(n - 1) (if we will run this code i expect to get fact will input 1 less so at some point we will get x=0 and it will terminate but can you explain the error i get while running fact(n) TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
your only return statement is return n*fact(n - 1) but when n==2 this is 2*fact(1) but what is fact(1) ? the way you defined the function it's nothing since the function is not defined for n<=1. Therefor Python sees 2*None ^ ^ int None which is a static semantic error
try doing type(fact(1)) and you will see it is the None type, because your function is not defined for n<=1
@TuringTest finally i got the concept thank you