Python recursive function call with if statement

2024/11/17 17:35:19

I have a question regarding function-calls using if-statements and recursion. I am a bit confused because python seems to jump into the if statements block even if my function returns "False"

Here is an example:

1    def function_1(#param):
2       if function_2(#param):
3           #do something
4           if x<y:
5               function_1(#different parameters)
6           if x>y:
7               function_1(#different parameters)

My function_2 returns "False" but python continues the code on line 5 for example. Can anyone explain this behavior? Thanks in advance for any answers.

edit: Sorry, forgot the brackets

concrete example:

1    def findExit(field, x, y, step):
2        if(isFieldFree(field, x, y)):
3            field[y][x] = filledMarker
4            findExit(field, x + 1, y, step+1)
5            findExit(field, x - 1, y, step+1)
6            findExit(field, x, y + 1, step+1)
7            findExit(field, x, y - 1, step+1)
8        elif(isFieldEscape(field, x, y)):
9            way.append(copy.deepcopy(field))
10            wayStep.append(step+1)def isFieldFree(field, x, y):if field[y][x] == emptyMarker:return Trueelse:return Falsedef isFieldEscape(field, x, y):if field[y][x] == escapeMarker:return Trueelse:return False

After both functions "isFieldFree" and "isFieldEscape" return False python continues the code in line 5 sometimes in line 6.

Answer

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.

https://en.xdnf.cn/q/118780.html

Related Q&A

How can I list all 1st row values in an Excel spreadsheet using OpenPyXL?

Using the OpenPyXL module with Python 3.5, I was able to figure out how many columns there are in a spreadsheet with:In [1]: sheet.max_column Out [1]: 4Then I was able to list the values in each of the…

Using matplotlib on non-0 MPI rank causes QXcbConnection: Could not connect to display

I have written a program that uses mpi4py to do some job (making an array) in the node of rank 0 in the following code. Then it makes another array in the node of rank 1. Then I plot both the arrays. T…

ioerror errno 13 permission denied: C:\\pagefile.sys

Below is my code, what I am trying to achieve is walking through the OS generating a MD5 hash of every file the code is functional, however, I receive the error in the title "ioerror errno 13 perm…

How can PyUSB be understood? [closed]

Its difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying thi…

Resize image in python without using resize() - nearest neighbor

For an assignment I want to resize a .jpg image with a python code, but without using the pil.image.resize() function or another similar function. I want to write the code myself but I cant figure out …

Concatenate two dataframes based on no of rows

I have two dataframes:a b c d e f 2 4 6 6 7 1 4 7 9 9 5 87 9 65 8 2Now I want to create a new dataframe like this:a b c d e f 2 4 6 6 7 1 4 7 9 9 5 8 That is, I only want the rows of the …

Having Problems with AzureChatOpenAI()

people. Im trying to use the AzureChatOpenAI(), but even if I put the right parameters, it doesnt work. Here it is: from langchain_core.messages import HumanMessage from langchain_openai import AzureCh…

Finding cycles in a dictionary

I have a dictionary which has values as:m = {1: 2, 7: 3, 2: 1, 4: 4, 5: 3, 6: 9}The required output should be cyclic values like 1:2 -> 2:1 = cycle, which both are present in dictionary. 4:4 is also…

Create a dataframe from HTML table in Python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 9…

Unable to load a Django model from a separate directory in a database script

I am having difficulty writing a python script that takes a directory of .txt files and loads them into my database that is utilized in a Django project. Based on requirements the python script needs …