This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed last year.
I am trying this code.
Function incre_test is recursive unless it satisfy the condition.
I expect 5 as result but it returns None.
What is the best practice for this pattern?
def incre_test(i):
if i > 4:
return i
i = i + 1
incre_test(i)
res = incre_test(0)
print(res) // why None???
Try this:
def incre_test(i):
while not i == 5:
i+=1
return i
res = incre_test(0)
print(res)
You have to use a while <bool>: loop to run a script (in this case i+=1) until the condition given is true.
Using a loop inside the function might do you better
such as
def incre_test(i):
while i < 5:
i += 1
return i
It's because your function is not returning anyting unless the parameter is greater than 4, so all you have to do is to add a return statement over the recursive call of the function, like this...
def incre_test(i):
if i > 4:
return i
return incre_test(i+1)
res = incre_test(0)
print(res)
Output:-
5
Related
This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 7 months ago.
Nothing is returned when I try iterating a function in Python.
Code is like this
def count(num):
if (num > 10):
return(num)
if(num<=10):
new = num + 1
count(new)
nummer = count(8)
If I do count(22), it returns 22. But when I do count(8), it doesnt return anything. I would like this function to return '11' but it return nothing.
Probably something wrong in my thinking but I really can't figure it out.
I hope someone can help me.
Thx,
Peter
Your second recursive call lacks a return statement, so that branch will always return None. You will need to explicitly return the result of count there, i.e.
return count(new)
You actually need to include a second return, in case your number is lower or equal than 10. Besides, you could have a slightly shorter code. Calling the function is not sufficient.
You are trying to evaluated whether a number x is greater or lower than 10. But this number can EITHER be greater OR lower. Therefore when you put
if num>10:
pass
you don't need another if statement, since if num is not greater than 10 it is lower or equal to 10.
def count(num):
if (num > 10):
return(num)
else:
new = num + 1
return count(new)
nummer = count(8)
you cannot return the value in other conditions. Try this
def count(num):
if (num > 10):
return(num)
if(num<=10):
new = num + 1
return count(new)
nummer = count(8)
This question already has answers here:
Why does my recursive function return None?
(4 answers)
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 2 years ago.
Below code returns "None"
But, when I change (return sum) to (return
print(sum)) it returns right value.
Why does this problem occur?
def good(num,sum):
if num == 0:
return sum
sum = sum + num
num = num - 1
good(num,sum)
sum = 0
a = 3
k = good(a,sum)
print(k)
The return statement is missing!
Do this:
def good(num,sum):
if num == 0:
return sum
sum = sum + num
num = num - 1
return good(num, sum)
This is because the function is called but is not returning the new values recursively.
One of the best website that explains this in depth and clearly is realpython.com, have a look especially at: maintaining-state but I suggest you to have a look at the whole article.
For sake of completeness I quote a section where I think is related to the issue you encountered:
Behind the scenes, each recursive call adds a stack frame (containing its execution context) to the call stack until we reach the base case. Then, the stack begins to unwind as each call returns its results.
unwind: Basically it returns it backward.
When dealing with recursive functions, keep in mind that each recursive call has its own execution context.
Other Stack Overflow Related questions
recursive-function-returning-none-in-python
python-recursion-with-list-returns-none
i-expect-true-but-get-none
This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 2 years ago.
def sel(unsort,current):
if len(unsort) == 0:
return current
temp = unsort[0]
for i in range(len(unsort)):
if unsort[i]<temp:
temp = unsort[i];
unsort.remove(temp)
current = current + [temp];
sel(unsort,current)
Above will define a function selection sort.
a = [4,3,2,1];
print(sel(a, []))
When I run the program on python, it print "None". The function should return current as a list. What have I done wrong here?
When you recursively call sel, you ignore the return value.
Change it to return:
return sel(unsort, current)
This question already has answers here:
Recursive method to find the minimum number in a list of numbers
(6 answers)
Closed 5 years ago.
I'm trying to find the minimum value in a list recursively. Since I'm still new in adapting to the recursive method, I would like to seek some help regarding my line of code:
listA = [9,-2,6,1,80,9,-2]
def findMinimum(l):
if len(l) == 1:
return l
else:
minNumber = findMinimum(l-1)
min = listA[0]
for i in listA:
if listA[i]<listA[i+1]:
min = listA[i]
return min
findMinimum(listA)
I'll appreciate if anyone could help me out as I'm relatively new to recursion and my understanding is definitely up to standard.
The first part of your function is correct. But you should change the second part like this:
listA = [9,-2,6,1,80,9,-2]
def findMinimum(l):
if len(l) == 1:
return l[0]
else:
return min(l[0], findMinimum(l[1:]))
findMinimum(listA)
Remember, recursive functions comes to make our codes simpler and easier.
The structure of your code is about right, but it has some mistakes. First, you should not be using listA inside of your function; listA is passed as an argument from the outside, and from within the function you should only refer to l. In the non-recursive case (where len(l) == 1), you should return l[0] (the minimum of a list with one element is that one element). Then, it is correct to call findMinimum inside your function again (that's the recursive call, as you know); however, what you probably want is to call it with the all the list l except the first element, that is, l[1:]. Then, you should compare the result minNumber to the first element of l; the idea is that you pick the smallest of l[0] and the minimum in l[1:]. Then you return the one you have chosen.
Additionally, you may want to consider the case when you get an empty list and throw an error; if you don't, you may get into an infinite recursion!
So a possible solution could be something like this:
listA = [9,-2,6,1,80,9,-2]
def findMinimum(l):
if len(l) == 0:
raise ValueError('Cannot find the minimum of an empty list.')
elif len(l) == 1:
return l[0]
else:
minNumber = findMinimum(l[1:])
min = l[0]
if minNumber < min:
min = minNumber
return min
findMinimum(listA)
This question already has answers here:
break and continue in function
(4 answers)
Closed 3 years ago.
My question is how can you break from outside a loop. If i can't is there a work around?
def breaker(numberOfTimesYouWantToBreak):
for i in range(0,numberOfTimesYouWantToBreak+1):
return break
while True:
for i in range(0,100000):
breaker(10)
print(i)
The result i want is:
11,12,13,14...
You cannot use the break statement anywhere else but directly in the loop. You cannot return it from another function, it is not an object to be passed around.
You appear to want to skip, not break from the loop, however. You are looking for the continue keyword instead:
for i in range(0,100000):
if i < 10:
continue
print(i)
If you must use a separate function, then have that function return True or False and use an if test to conditionally use continue:
def should_skip(i):
return i < 10
for i in range(0,100000):
if should_skip(i):
continue
print(i)
It's impossible.
The workaround is to put your code into a function and return from the function.
You can't break externally, however, for the same effect you can do this:
for i in range(0,100000):
i += 10 + 1 #(10 is the number you wanted in the break function)
print(i)