Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading