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
Related
Is it possible to check dynamically whether a function has been called from within a loop?
Example:
def some_function():
if called_from_loop:
print("Hey, I'm called from a loop!")
for i in range(0, 1):
some_function()
some_function()
Expected output:
> Hey, I'm called from a loop!
Not sure if this is going to be 100% reliable. It's also rather cumbersome and would have to be written inside the function of interest rather than in its own discrete function for fairly obvious reasons.
We can get the source code for the currently executing .py file
We can also get a stack trace.
Therefore, we can determine the line number in the code from where our function has been called. Thus we can navigate the source code (backwards) taking care to note indentation and see where the indentation decreases and if the line where that occurs starts with either 'for' or 'while' then we were called from within a loop.
So here's the fun:
import traceback
import inspect
import sys
def getws(s):
return len(s) - len(s.lstrip())
def func():
source = inspect.getsource(sys.modules[__name__]).splitlines()
stack = traceback.extract_stack()
lineno = stack[-2].lineno-1
isLooped = False
if (ws := getws(source[lineno])) > 0:
for i in range(lineno-1, -1, -1):
if (_ws := getws(line := source[i])) < ws:
if (tokens := line.split()) and tokens[0] in {'for', 'while'}:
isLooped = True
break
if (ws := _ws) == 0:
break
print('Called from loop' if isLooped else 'Not from loop')
def looper():
for _ in range(1):
# banana
func()
def looper2(): # this code is nonsense
i = 5
while i > 0:
if i < 10:
func()
break
looper()
looper2()
func()
while True:
func()
break
if __name__ == '__main__':
func()
Output:
Called from loop
Called from loop
Not from loop
Called from loop
Not from loop
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.
Is the below code valid in python or its not possible to extract variable in python and perform checks on it in one line?
def method1(self,some_text):
"""For illustration purpose it returns a hard coded value"""
return (1,2)
if x = method1("Hello") and x[0] == 1 and x[1] = 2:
print("This is it {},{}".format(x[0],x[1]))
elif x = method1("World") and x[0] == 3 and x[1] = 4:
print("This is it, second {},{}".format(x[0],x[1]))
elif x = method1("The") and x[0] == 5 and x[1] = 6:
print("This is it, third {},{}".format(x[0],x[1]))
else:
print("No match")
Currently I have this if condition for multiple attribute to check. Since python throws error because its not a valid syntax, I have to declare all such property above the if statement and so many attributes being declared in the local block.
Any better way or suggestion, to have extract the variable and have checks in one line as well as use the attribute within if block?
Check this:
def method1(some_text):
"""For illustration purpose it returns a hard coded value"""
return (1,2,3)
def printres(x):
for i in x:
res=method1(i[0])
if res[:2]==i[1]:
print(i[2].format(res[2]))
return
else:
print("No match")
printres([("Hello",(1,2),"This is it {}"),("World",(3,4),"This is it, second {}"),("The",(4,5),"This is it, third {}")])
Here is my code:
def getRow(rowIndex):
if rowIndex == 0:
return [1]
if rowIndex == 1:
return [1,1]
def f(n,r):
if n == 1:
print(r)
return r
r = [1]+[r[i] + r[i+1] for i in range(len(r)-1)]+[1]
f(n-1,r)
return f(rowIndex,[1,1])
print(getRow(4))
That print(r) function worked perfectly and gave the right answer, however, the return r statement just didn't work at all. Anyone knows why is this happening?
Desired output: [1,4,6,4,1]
Actual output: null
I would like to know why doesn't the return r statement in the f function return anything through the return f(rowIndex,[1,1]) statement.
the return r statement just didn't work at all
If the print works, then the return works. However, it only works when n == 1.
In all other cases, your function will essentially return None (not null) since you have no other return statement within the f function body.
Perhaps you can try return f(n-1,r) rather than simply calling the function and ignoring the return result
Sometimes I get confused as to where to use the return statement. I get what it does, it's just that I don't get its placement properly.
Here's a short example of the same code.
Correct way:
def product_list(list_of_numbers):
c = 1
for e in list_of_numbers:
c = c * e
return c
Wrong way (which I did initially):
def product_list(list_of_numbers):
c = 1
for e in list_of_numbers:
c = c * e
return c
Can someone clarify what's the difference between the two and where should the return be when using a loop in a function?
return in a function means you are leaving the function immediately and returning to the place where you call it.
So you should use return when you are 100% certain that you wanna exit the function immediately.
In your example, I think you don't want to exit the function until you get the final value of c, so you should place the return outside of the loop.
You're putting too much emphasis on the impact of return on controlling the behaviour of the for loop. Instead, return applies to the function and happens to terminate the for loop prematurely by primarily bringing an end to the function.
Instead, you can control the behaviour of the for loop independently from the function itself using break. In addition, you can have multiple return statements in a function depending on what action should be taken in response to particular criteria (as in my_func1). Consider the following:
import random
def my_func1(my_list, entry):
'''
Search a list for a specific entry. When found, terminate search
and return the list index immediately
Return False if not found
'''
print "\n Starting func1"
index = 0
for item in my_list:
if item != entry:
print "Not found yet at index: {}".format(index)
index += 1
else:
print "found item, at index {}".format(index)
print "Terminating function AND loop at same time"
return index
print "########### ENTRY NOT IN LIST. RETURN FAlSE #############"
return False
a = my_func1(['my', 'name', 'is', 'john'], 'is')
b = my_func1(['my', 'name', 'is', 'john'], 'harry')
def my_func2(my_list):
''' Iterate through a list
For first 4 items in list, double them and save result to a list that will
be returned, otherwise terminate the loop
Also, return another list of random numbers
'''
print '\n starting func2'
return_list = []
for i in range(len(my_list)):
if i < 4:
print 'Value of i is {}'.format(i)
return_list.append(my_list[i] * 2)
else:
print 'terminating for loop, but ** keep the function going **'
break
other_list = [random.randint(1, 10) for x in range(10)]
print 'Returning both lists'
return return_list, other_list
c = my_func2([x for x in range(10)])