'Python print the value of specific parameter in the function

I only want to return and print the error when the function is called, but it seems that the whole functions are being run when I print the function.

My expected output is only:

false    
list index out of range

but I am getting:

false
false
false
list index out of range

I tried calling the function like this but did not work: print(test(error))

Question: How can I only print the error parameter and not the other parameter outside the function? Here is my code, Thanks:

def test(error=None, parameter1=None):
       array = []

       try:
              if parameter1 == True:
                     print("true")
                     array[0]
              else:
                     print("false")
                     array[0]
       except Exception as e:
              error = e
              return error
test()
if test() is not None:
       print(test())


Solution 1:[1]

You're running the function twice, once in the if statement, and then again in the print() statement.

If you only want to run it once, assign the result to a variable.

err = test()
if not err:
    print(err)

Solution 2:[2]

This is happening because python is read line by line. This means that it will check the condition for parameter1 == True before going onto your statement that returns an error. Restructure the code so that it checks for an error before printing out "false". Example:

def test(error=None, parameter1=None):
       array = []
       
       try:
              array[0]
       except Exception as e:
              error = e
              return error
             
       if parameter1 == True:
              print("true")
       else:
              print("false")

       

if test() is not None:
    print(test())

Additionally, the act of writing the if test() will call the function, which is why it printed false the first time. Then you called print(test()) which called it a second time, resulting in two "false"s being printed out.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Barmar
Solution 2 Alan Shiah