Python Recursive Function Call With If Statement
Solution 1:
Short answer:
That's because you're not actually calling the function. You can call the function by using the parenthesis.
if function2():
...
Long answer:
Functions in Python are a first class citizen (functional paradigm), and so it is completely valid to refer to a function just by its name. The following is valid syntax:
def hello():
print("Hello")
hello_sayer =hello
hello_sayer()# print "Hello"
The next concept in play is truth-ness of non-Boolean variables. In Python, the following are considered False-y
- None
- False
- zero of any numeric type, for example, 0, 0L, 0.0, 0j.
- any empty sequence, for example, '', (), [].
- any empty mapping, for example, {}. instances of user-defined classes, if the class defines
- a nonzero() or len() method, when that method returns the integer zero or bool value False.
Everything else is True-ish. Since a function name falls under none of the above categories, it is considered True-ish when tested in a conditional context.
Reference: https://docs.python.org/3/library/stdtypes.html#truth-value-testing
Edit: The earlier question was incomplete, and did not have a function call. For the new question, AChampion's answer is the correct one.
Solution 2:
You may misunderstand how recursion works, yes it continues at line 5 or 6 because the recursion has ended at a lower level in the call stack, so it continues at a higher-level in the call stack. Here's a sample call stack, note the next operation after False
is the next findExit()
at the higher call stack:
1 findExit(...):
2True:
3 field assignment
4.1 findExit(x+1)
2True3 field assignment
4.1 findExit(x+1):
2False# Does not jump to line 5 in current call stack.5.1 findExit(x-1):
. ...
Post a Comment for "Python Recursive Function Call With If Statement"