python - Function for CodeAcademy course returning absolute value for numbers produces error about maximum recursion depth -


my code should use abs() return absolute value of argument (called distance_from_zero(n)) when argument either 'int' or 'float'. if argument else, 'str' code should return "nope".

when run code on codeacademy, error message

"oops, try again. looks have error in code. check error message more info! - maximum recursion depth exceeded".

can please tell me how following code wrong?

def distance_from_zero(n):     return distance_from_zero(n)      if type(n) == int or type(n) == float:         return abs(n)      else:         return "nope" 

edit: has been fixed, thank you!

you've defined function endlessly calls first action, overflows stack. that's "maximum recursion depth exceeded" means.

def distance_from_zero(n):     return distance_from_zero(n)  # calls calls ...     # , doesn't matter else happens in function, it'll never     # executed 

return end point of function. once reaches return statement, function ends. putting return <anything @ all> @ start of function doesn't make sense.

also, aside: don't test type(foo) == some_type, test isinstance(foo, some_type). plays nicely inheritance.

from collections import defaultdict  d = defaultdict(list)  type(d) == dict  # false isinstance(d, dict)  # true # you'll never want treat defaultdict non-dict entity 

Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -