This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
How can I use `return` to get back multiple values from a loop? Can I put them in a list?
(2 answers)
Closed 7 months ago.
Very new to programming.
Wondering why does this example print all the items in the list, while the second example prints only the first?
def list_function(x):
for y in x:
print(y)
n = [4, 5, 7]
list_function(n)
def list_function(x):
for y in x:
return y
n = [4, 5, 7]
print(list_function(n))
Your first example iterates through each item in x, printing each item to the screen. Your second example begins iterating through each item in x, but then it returns the first one, which ends the execution of the function at that point.
Let's take a closer look at the first example:
def list_function(x):
for y in x:
print(y) # Prints y to the screen, then continues on
n = [4, 5, 7]
list_function(n)
Inside the function, the for loop will begin iterating over x. First y is set to 4, which is printed. Then it's set to 5 and printed, then 7 and printed.
Now take a look at the second example:
def list_function(x):
for y in x:
return y # Returns y, ending the execution of the function
n = [4, 5, 7]
print(list_function(n))
Inside the function, the for loop will begin iterating over x. First y is set to 4, which is then returned. At this point, execution of the function is halted and the value is returned to the caller. y is never set to 5 or 7. The only reason this code still does print something to the screen is because it's called on the line print list_function(n), so the return value will be printed. If you just called it with list_function(n) as in the first example, nothing would be printed to the screen.
For functions return terminates the execution, therefore nothing will be executed after return.
In your case the first function will print all the items because there is nothing that breaks the process. However in the second function it will return and end the process.
Related
This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 1 year ago.
I have made 2 functions: one to generate random values from 0 to 20, and another to check if the value generated by function random matches the value of list. If the value matches then random should start again to produce new value
My code is:
import random
mylist=[6,2,4]
y=int()
def randoom():
str=random.randint(0,20)
return str
def checklist():
y=randoom()
print(y,"Generated value y")
if y in mylist:
print(y,"already exist in list")
checklist()
if y not in mylist:
return y
for b in range(1,10):
x=checklist()
print(x," X got the value")
mylist.append(x)
print(mylist)
My output is: [6, 2, 4, 5, 12, 7, 16, 13, None, 17, 19, None]
Why is None getting appended?
I tried everything in last 3 days to figure out why None is getting appended in list even when I made sure the function runs again to produce a new value of y if it matches the list.
Your checklist function can return None if y is in mylist:
if y in mylist:
print(y,"already exist in list")
checklist() # Executes checklist again, but discards the return value
There is no path after this that can return a value, so the function returns None. You can fix this by returning checklist():
if y in mylist:
print(y,"already exist in list")
return checklist() # Executes checklist again, but returns the value
The return value of checklist is not being saved in your variable after being executed. Fixing this should make your Code work.
Still, you have at the very top of your program a variable named str. Since str is also a function in python, this could cause issues down the road. I would recommend to change this.
I defined a function that prints multiple values as lists, I've written it in such a way that the first value in the list is x and the other is the result of a specific equation.
The first problem is that when I use return instead of print(), I am only getting the first iteration of the loop, unlike print() which prints everything (which is what I want)
Second, I want to pick certain results that come from this loop function:
I want to pick the results with the smallest value of the second item in the list. For example in [12, 2], [13, 1], [14, 5], I want to write a function that returns or prints [13, 1] as 1 is the smallest. The first term in the list is just for observation.
I also want to make a list or just return values of the top 10 items with the smallest second value.
def temporary3(ratio,x,y):
results = []
for x in range(1,x):
results.append(abs((1200*math.log((2**(x/y)),2)-(1200*math.log(ratio,2)))))
return results
def intApprox(ratio,x):
return min(temporary3(ratio,x,x))
def tempFinder(ratio):
list1 = []
for x in range(12,61,1):
list1.append(intApprox(ratio,x))
print([x,round(intApprox(ratio,x),3)])
Then we can try the code:
tempFinder(5/4)
We get something like:
Thank you very much!!
"return statement causes execution to leave the current subroutine"
Your for loop stops after the return statement, it doesn't do the second execution because a return statement kills the loop and the function running it.
This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 7 months ago.
I am creating a program that accepts an array and reverses it, it must include a recursive function. I am having an issue where it is returning None instead of the reversed array. Running it through a debugger and creating stop points at the return and the call of the recursive function shows that it does indeed reverse the function properly, but fails to return the array, is there something I am missing or have done wrong for it to not return the array?
Code:
def reverse(my_list, index = 0):
if index == len(my_list)//2: #The program will return the list as soon as it reaches the middle entry
return my_list
elif index <len(my_list)/2:
temp = my_list[index]
my_list[index] = my_list[(len(my_list)-1)-index]
my_list[(len(my_list)-1)-index] = temp
reverse(my_list,index+1)
def main():
myList = [0,1,2,3,4,5,6,7,8,9]
print(str(myList))
print(str(reverse(myList)))
if __name__ == '__main__':
main()
This is actually a Data structure and algorithm lesson about stacks and recursion.
function calls are stored on the call stack. The call stack is a specific implementation of the stack data structure.
It is a LIFO (Last in, first out) data structure, meaning that function calls placed on the top of the call stack are also the first to be popped off.a stack is like a deck of cards. It is more convenient to place and draw cards from the top of the stack of cards.
in other words you can think of it as a plate that every piece of data gets stacked over the other one . So when you call recursion every time the function is called the data is stored on the call stack on top of each other like layers So the last condition that ends the recursion and return the value is on the top stack but once the return method is called the stacks gets destroyed to free up memory
remember
The first stack that gets destroyed is the top one which has the data and it keeps going till the last stack which has no data to return so it returns None So in order to make the script save the data you have on the top stack you have to return that stack's value which it will pass the saved data from one stack to another till the break of recursion
You need to return the recursive result:
return reverse(my_list,index+1)
otherwise the function simply ends after executing that statement, resulting in None being returned.
In Python, any function that ends without a return statement
implicitly returns None.
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
As Thierry Lathuille already said, you missed a return in line 8, so that you correct code should look like this:
def reverse(my_list, index=0):
if index == len(my_list) // 2: # The program will return the list as soon as it reaches the middle entry
return my_list
elif index < len(my_list) / 2:
temp = my_list[index]
my_list[index] = my_list[(len(my_list) - 1) - index]
my_list[(len(my_list) - 1) - index] = temp
return reverse(my_list, index + 1)
def main():
myList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(str(myList))
print(str(reverse(myList)))
if __name__ == '__main__':
main()
This question already has answers here:
What is the difference between `sorted(list)` vs `list.sort()`?
(7 answers)
Closed 4 years ago.
I was trying to sort list elements inside a function without return when I try to print the list by its name it does not get sorted, but it is sorted inside a function.
I have to update the list inside the function without returning
def sort(n):
n.append(10)
sorted(n)
n = [5,1,2,3]
print(n)
Expected : [1,2,3,5]
actual: [5,1,2,3]
I'm sorry, I made a series of mistakes myself. It's a lesson for me too.
def isort(n):
n.append(10)
n.sort() #I used n[:] = sorted(n), but it's superfluous.
n = [5,1,2,3]
isort(n)
print(n)
m = [7,9,3,13]
isort(m)
print(m)
output:
[1, 2, 3, 5, 10]
[3, 7, 9, 10, 13]
sort is an existed fuction in python, need to change it to other name. I changed to isort.
We have to call the function isort to let it do its work.
We need to update the elements in the list to make the list update. [:] Slice notation here.
It's better to use different name between function argument and the call. (n and m here).
Many thanks to DYZ, Primusa, and Tomothy32 :)
I am working on a code golf and attempting to write a recursive function using the tuple boolean evaluation syntax ((a,b)[bool]). My function is as follows (with some helpful prints):
def b(A,k,n):
m=len(A)/2
print "A: ", A
print "m: ", m
print "n: ", n
print "A[m]", A[m]
if A[m]==k:return m+n
# return (m+n,(b(A[m:],k,m+n),b(A[:m],k,n))[A[m]<k])[A[m]!=k]
return m+n if A[m]==k else (b(A[:m],k,n) if A[m]>k else b(A[m:],k,m+n))
Arguments A, k, and n are the input list to search, the key, and the index in the original A which a sublist starts at. m is the middle entry of the list. If I search [1,2,3,4,5,6,7] for 6, I would expect to see the following output
A: [1, 2, 3, 4, 5, 6, 7]
m: 3
n: 0
A[m] 4
A: [4, 5, 6, 7]
m: 2
n: 3
A[m] 6
The correct output and result are produced with the non-commented return statement. However, when I attempt to use the commented return statement (which should be equivalent), I receive a recursion depth error.
Moreover, if I replace one of the recursive calls with a determinate value, then search for a value on the edge, it functions as expected. For example, searching for 6 in [1,2,3,4,5,6,7] works correctly if my return statement is:
return (m+n,(b(A[m:],k,m+n),"anyValue")[A[m]>k])[A[m]!=k]
"anyValue" is never returned by my conditional in this case, so why does it matter what value I put in there?
Why do these two statements evaluate differently?
When you do
thing() if condition else other_thing()
only one of thing() and other_thing() is evaluated. The one that isn't returned doesn't get evaluated at all, so you can do things like
base_case_value if base_case_condition else continue_recursing()
and the recursion will stop at the base case.
When you do
(continue_recursing(), base_case_value)[base_case_condition]
Python needs to build the tuple before it can be indexed, so both base_case_value and continue_recursing() are evaluated no matter what. Your function doesn't stop when it hits the base case.
The problem is that the two statements aren't equivalent. In the working "if" case, you only call b once per round. In the commented out "tuple boolean" case, you evaluate both b conditions before selecting which one to use with the boolean selector. Since b is recursive, and you always run the "bad" non terminating side along with the "good" terminating side, you get max recursion error.