Python print the value of specific parameter in the function - python

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())

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)

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.

Related

Not Printing anything on screen

def even_number_list(even_list):
for i in even_list:
if i % 2 == 0:
return True
else:
pass
even_number_list([1,3,5,6,9])
This code is not printing anything on the screen, I believe that it should print True, please help a beginner.
Thanks,
I think I'll get an output, True
Your function, as you expect, should return True. But when you call it, you don't use the return value. If you want to print the return value, you need to call even_number_list() inside of a print() function to print the output or assign the function call to a variable.
def even_number_list(even_list):
for i in even_list:
if i % 2 == 0:
# Return True if one even number is found
return True
# Return False if all numbers in even_list are odd
return False
# Call function even_number_list() returns True but is not assigned to anything
even_number_list([1,3,5,6,9])
# Assign return value to output
output = even_number_list([1,3,5,6,9])
# Print the output
print(output)
# Or in one step:
print(even_number_list([1,3,5,6,9]))
I also removed your else condition, as the pass statement does nothing.
And in addition, if no even number is found your function returns False now.

Python - using returns in conditional statements

I want to use return instead of print statements but when I replace the print statements with return I don't get anything back. I know I'm missing something obvious:
def consecCheck(A):
x = sorted(A)
for i in enumerate(x):
if i[1] == x[0]:
continue
print x[i[0]], x[i[0]-1]
p = x[i[0]] - x[i[0]-1]
print p
if p > 1:
print "non-consecutive"
break
elif x[i[0]] == len(x):
print "consecutive"
if __name__ == "__main__":
consecCheck([1,2,3,5])
-----UPDATE------ HERE IS CORRECTED CODE AFTER TAKING HEATH3N's answer:
def consecCheck(A):
x = sorted(A)
for i in enumerate(x):
if i[1] == x[0]:
continue
print x[i[0]], x[i[0]-1]
p = x[i[0]] - x[i[0]-1]
print p
if p > 1:
a = "non-consecutive"
break
elif x[i[0]] == len(x):
a = "consecutive"
return a
if __name__ == "__main__":
print consecCheck([4,3,7,1,5])
I don't think you understand what a return statement does:
A return statement causes execution to leave the current subroutine and resume at the point in the code immediately after where the subroutine was called, known as its return address.
You need to wrap consecCheck([1,2,3,5]) in a print statement. Otherwise, all it does it call the function (which no longer prints anything) and goes back to what it was doing.
print takes python object and outputs a printed representation to console/output window
when return statement used in function execution of program to calling location, also if function execution reaches to return statement then no other line will be executed. read detail difference between print and return
So In your case if you want to show result in output console you may do it as following example:
def my_function():
# your code
return <calculated-value>
val = my_function()
print(val) # so you can store return value of function in `val` and then print it or you can just directly write print(my_function())
In your code you are printing values and continuing execution in that case you might consider using yield keyword suggested by #COLDSPEED or just use print to all statement except last one

Python try finally block returns [duplicate]

This question already has answers here:
Weird Try-Except-Else-Finally behavior with Return statements
(3 answers)
Closed 9 years ago.
There is the interesting code below:
def func1():
try:
return 1
finally:
return 2
def func2():
try:
raise ValueError()
except:
return 1
finally:
return 3
func1()
func2()
Could please somebody explain, what results will return these two functions and explain why, i.e. describe the order of the execution
From the Python documentation
A finally clause is always executed before leaving the try statement, whether an exception has occurred or not. When an exception has occurred in the try clause and has not been handled by an except clause (or it has occurred in a except or else clause), it is re-raised after the finally clause has been executed. The finally clause is also executed “on the way out” when any other clause of the try statement is left via a break, continue or return statement. A more complicated example (having except and finally clauses in the same try statement works as of Python 2.5):
So once the try/except block is left using return, which would set the return value to given - finally blocks will always execute, and should be used to free resources etc. while using there another return - overwrites the original one.
In your particular case, func1() return 2 and func2() return 3, as these are values returned in the finally blocks.
It will always go to the finally block, so it will ignore the return in the try and except. If you would have a return above the try and except, it would return that value.
def func1():
try:
return 1 # ignoring the return
finally:
return 2 # returns this return
def func2():
try:
raise ValueError()
except:
# is going to this exception block, but ignores the return because it needs to go to the finally
return 1
finally:
return 3
def func3():
return 0 # finds a return here, before the try except and finally block, so it will use this return
try:
raise ValueError()
except:
return 1
finally:
return 3
func1() # returns 2
func2() # returns 3
func3() # returns 0
Putting print statements beforehand really, really helps:
def func1():
try:
print 'try statement in func1. after this return 1'
return 1
finally:
print 'after the try statement in func1, return 2'
return 2
def func2():
try:
print 'raise a value error'
raise ValueError()
except:
print 'an error has been raised! return 1!'
return 1
finally:
print 'okay after all that let\'s return 3'
return 3
print func1()
print func2()
This returns:
try statement in func1. after this return 1
after the try statement in func1, return 2
2
raise a value error
an error has been raised! return 1!
okay after all that let's return 3
3
You'll notice that python always returns the last thing to be returned, regardless that the code "reached" return 1 in both functions.
A finally block is always run, so the last thing to be returned in the function is whatever is returned in the finally block. In func1, that's 2. In func2, that's 3.
func1() returns 2. func2() returns 3.
finally block is executed finally regardless of exception.
You can see order of execution using debugger. For example, see a screencast.

What's the point of the return in this code?

So, I have this function below:
def remove_all(lst):
i = 0
while i < 10:
try:
print('Removing... ')
print(int(lst.pop()) + 10)
print("Removed successfully.")
# As soon as an IndexError is raised, jump to the following block of code...
except IndexError as err:
# if you encounter an indexerror, do the following:
print("Uh oh! Problems.")
return
#As soon as a Value error is raised, jump here.
except ValueError as err:
print("Not a number")
i = i + 1
What does the return do? There is no value after the return, so does it mean None or True?
And what is the point of having the return there if the value is none?
Thanks!
The return value is None.
In this context, the function never returns a value. The point of the return is to stop execution
The return statement can be used as a kind of control flow. By putting one (or more) return statements in the middle of a function, you could exit/stop the function.
This causes the function to exit when an IndexError is encountered, just without returning any value.
In your example, there is no return value.
Given you would call the function like this:
a = remove_all(lst)
a will be None because the function simply returns nothing.
To check the success of the function, you could implement it like this:
def ....
try:
...
exception 1:
your error handling...
return False
exception 2:
your error handling...
return False
continue function...
return True
When you then check the return value of your function, you will see if it has been executed till the end (True) or if it raised an error before (False).
However, this will not continue the execution of this particular function after one of the defined errors occurred.

Handling assertion in python

I can't understand why this code:
x='aaaa'
try:
self.assertTrue(x==y)
except:
print (x)
generates me this error
AssertionError: False is not True
It should be handle it by
print(x)
EDIT
original code is:
try:
self.assertTrue('aaaa'==self.compare_object_name[1])
except:
print ('aaa')
#Space_C0wb0y I can't give you full code because it is not my code, and I don't have a permission.
You should include the code that defines the assertTrue method. From the output you get, I'd say that it actually does not throw an exception, but deals with it internally (thus the error message being printed, and not your value).
You can use the built-in assert statement of Python, which works as expected:
x = 'aaaa'
y = 'bbb'
try:
assert(x == y)
except:
print (x)
Output:
>>>
aaaa

Categories