exception - return inside an except python -
what problem when including function inside except? in case have following function:
def inventedfunction(list1): print "initial list %r" %list1 creates list2 based on list1 try: list2[1] print "inside try %r" %list2 inventedfunction(list2) except: print "inside except %r" %list2 return list2
after running inventedfunction(somelist) seems working:
initial list [3, 562, 7, 2, 7, 2, 3, 62, 6] inside try [[3, 562], [2, 7], [2, 7], [3, 62], [6]] initial list [[3, 562], [2, 7], [2, 7], [3, 62], [6]] inside try [[2, 3, 7, 562], [2, 3, 7, 62], [6]] initial list [[2, 3, 7, 562], [2, 3, 7, 62], [6]] inside try [[2, 2, 3, 3, 7, 7, 62, 562], [6]] initial list [[2, 2, 3, 3, 7, 7, 62, 562], [6]] inside except [[2, 2, 3, 3, 6, 7, 7, 62, 562]]
but not returning anything. if include return list2 outside except returns [[3, 562], [2, 7], [2, 7], [3, 62], [6]] not [[2, 2, 3, 3, 6, 7, 7, 62, 562]] want.
also if change code this:
if len(list2)!=1: inventedfunction(list2) else: return list2
there no return in function.
another simple example doesn't return anything:
def inventedfunction(list1): list2=list1[:-1] if len(list2)!=1: inventedfunction(list2) else: return list2
you recursively calling function - inventendfunction()
- never returning result recursive call, hence not return , need return result returned recursive call -
try: list2[1] print "inside try %r" %list2 return inventedfunction(list2)
also, bad have bare except
, should think exception can come when calling inventedfunction()
, except exceptions.
since in comments -
i guess problem doesn't have function understanding how recursion works.
lets take simple example of function a()
recursion , similar yours -
>>> def a(i): ... if == 1: ... return "hello" ... else: ... a(i+1) ... >>> print(a(0)) none
as can see above simple example returned 0
, why? lets take step step -
main -> a(0)
you call function
a(0)
, herei
0 , go else part , , calla(1)
.main -> a(0) -> a(1)
now, in
a
again,i
1
, goif
part, , returns"hello"
.main -> a(0) #returned a(0)
now after return not directly return
main()
calleda(0)
, no returns whereever functiona(1)
called, , insidea(0)
, returna(0)
, , execution continues, sincea(0)
not return anything, default return value inmain
, `none.
for example again, need add return inventedfunction(list2)
, correctly return results recursive calls, otherwise return value of recursed calls thrown away , not returned back. example -
def inventedfunction(list1): list2=list1[:-1] if len(list2)!=1: return inventedfunction(list2) else: return list2
Comments
Post a Comment