nothing returned in iterating Python function [duplicate] - python

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)

Related

Why Recursive function return "None" [duplicate]

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

Calculating a factorial using loops in Python3

I am currently studying Software Development as a beginner and I have a task in my programming class to calculate and display a factorial using a loop. I've been given the pseudo-code and have to translate it into true code and test it in the REPL to make sure it returns the expected results.
I almost have it but I've run into two issues that I just can't seem to resolve.
1) The function is returning an extra line of "None" after the calculation and
2) The answer is displaying over multiple lines when I want it to display on a single line.
My current code (which does return the correct answer) is as follows:
def calcFactorial(number):
factorial = 1
print(str(number)+"! =", number)
for count in range (1, number):
if number-count > 0:
factorial = factorial*number-count
print("x", str(number-count))
factorial = factorial*number
print("=", factorial)
When I test, using 3 for example, the REPL returns the following:
>>> print(calcFactorial(3))
3! = 3
x 2
x 1
= 12
None
So I have the correct answer but with an extra line of "None" which I would like to remove (I believe it has something to do with the print function?) and I don't know how to format it correctly.
Any help would be much appreciated.
your function calcFactorial(3) prints already, so you shouldn't call it with
print(calcFactorial(3))
just call it with
calcFactorial(3)
without the print function.
you might think about calling the function calc_and_print_factorial() in order to make it clear, that this function does already the printing
Regarding your second question:
Blockquote
2) The answer is displaying over multiple lines when I want it to display on a single line.
You can fix it by using a single print statement:
def calcFactorial(number):
factorial = 1
string = str(number) + "! = " + str(number)
for count in range (1, number):
if number-count > 0:
factorial = factorial*(number-count)
string = string + " x " + str(number-count)
factorial = factorial * number
print(string + " = " + str(factorial))
This will give you:
IN: calcFactorial(3)
OUT: 3! = 3 x 2 x 1 = 6
On a side note: you might want to think of how to implement this recursively. Maybe that comes later in your class but this would be one of the first go-to examples for it.
Adding to the blhsing's answer, you should choose between these built-in ways to print the "returned" value.
First way:
def calcFactorial(number):
... # <- Your function content
return factorial
Then, call your function with a print() to get the explicitly returned value, as you can see in the return factorial line. See this reference for more details:
print(calcFactorial(3))
Second way:
Having the same function definition with its return statement, just call the function with its instance statement:
calcFactorial(8)
By default, python will print the returned value without a print()
Third way:
Just call the function (without the explicit return statement, this will return a "None" (null-like) value by default), using the print() method. Do NOT use print() inside another print().
Your calcFactorial function does not explicitly return a value, so it would return None by default, so print(calcFactorial(3)) would always print None.
You should make the calcFactorial function return factorial as a result at the end:
def calcFactorial(number):
factorial = 1
print(str(number)+"! =", number)
for count in range (1, number):
if number-count > 0:
factorial = factorial*number-count
print("x", str(number-count))
factorial = factorial*number
print("=", factorial)
return factorial
So I have the correct answer but with an extra line of "None" which I would like to remove
You are printing the return value from your function. In this case, you haven't specified a return value with a return statement so the function automatically returns None.
To fix the problem, you should return a value from your function. Note that you don't need to call print() for final answer because the REPL already does this for you.
Note that the REPL will automatically print the return value for you, so you can just type calcFactorial(3) instead of print(calcFactorial(3)).
Additionally, you are not getting the correct answer. You should get 6 instead of 12. It looks like you are trying to count down from number and multiplying each number together. You can get the same result by counting up from 1. This will lead to much simpler code and avoid the error.
If you want to understand why your code isn't doing the correct thing, look closely at factorial = factorial*number-count and think about the order of operations that are used to calculate the result here.

Python: My Return statement always returns None [duplicate]

This question already has answers here:
Python Script returns unintended "None" after execution of a function [duplicate]
(3 answers)
Closed 6 years ago.
This is a function that is able to take in a binary number as a string and convert it into a decimal number. For some reason, this function always returns None and I can not understand why this is happening. If anyone could provide me with an explanation it would be much appreciated.
total = 0
power = 0
def binaryToDecimal(binaryString):
global total, power
n = len(binaryString) - 1
if n < 0:
return total
else:
if binaryString[n] == '1':
total += (2 ** power)
power += 1
binaryToDecimal(binaryString[:-1])
The final line needs to be return binaryToDecimal(binaryString[:-1]). At the moment you're returning total from the last call, but none of the preceding calls are returning anything.
Instead of recursive call for that, just a for loop like below should do
def binaryToDecimal(binaryString):
total=0
# strip of 0b if there is any
binaryString = binaryString.lstrip('0b')
n=len(binaryString)
for i in range(n):
# index from lsb bit to msb
if binaryString[n-1-i] == '1':
total += (2 ** i)
return total
Alternatively, its recommended to just use python built in int function
def binaryToDecimal(binaryString):
return int(binaryString, 2)

Variable Scope Issue in Python

I am new to Python and I have been working with it for a bit, but I am stuck on a problem. Here is my code:
def collatz(num,ctr):
if(num != 1):
ctr+=1
if(num%2==0):
collatz(num/2,ctr)
else:
collatz(num*3+1,ctr)
return ctr
test=collatz(9,0)
For any number I put in for num, let's say 9 for instance, and 0 for ctr, ctr always comes out as 1. Am I using the ctr variable wrong?
EDIT:
I am trying to print out how many times the function is recursed. So ctr would be a counter for each recursion.
The variable ctr in your example will always be 1 because of the order of the recursive call stack. As one value of ctr is returned, then the call stack will start returning the previous values of ctr. Basically, at the very last recursive call, the highest value of ctr will be returned. But since the method call at the bottom of the call stack returns the very last value aka the value that will be stored in test, test will always be 1. Let's say I input parameters into collatz that would result in five total calls of the method. The call stack would look like this coming down,
collatz returns ctr --> 5
collatz returns ctr --> 4
collatz returns ctr --> 3
collatz returns ctr --> 2
collatz returns ctr --> 1 //what matters because ctr is being returned with every method call
As you can see, no matter how many times collatz is called, 1 will always be returned because the call at the bottom of the call stack has ctr equaling 1.
The solution can be a lot of things, but it really depends on the purpose of what you're trying to accomplish which isn't clearly stated in your question.
EDIT: If you want ctr to end up being the number of times a recursive call is made, then just assign ctr to the value of the method call. It should look like this,
def collatz(num,ctr):
if(num != 1):
ctr+=1
if(num%2==0):
ctr = collatz(num/2,ctr)
else:
ttr = collatz(num*3+1,ctr)
return ctr
test=collatz(9,0)
I changed your recursive calls to set the value received back from the recursive calls into ctr. The way you wrote it, you were discarding the values you got back from recursing.
def collatz(num,ctr):
if(num != 1):
ctr+=1
if(num%2==0):
ctr=collatz(num/2,ctr)
else:
ctr=collatz(num*3+1,ctr)
return ctr
test=collatz(9,0)
An example:
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
elif number % 2 == 1:
result = 3 * number + 1
print(result)
return result
n = input("Give me a number: ")
while n != 1:
n = collatz(int(n))
Function parameters in Python are passed by value, not by reference. If you pass a number to a function, the function receives a copy of that number. If the function modifies its parameter, that change will not be visible outside the function:
def foo(y):
y += 1
print("y=", y) # prints 11
x = 10
foo(x)
print("x=", x) # Still 10
In your case, the most direct fix is to make ctr into a global variable. Its very ugly because you need to reset the global back to 0 if you want to call the collatz function again but I'm showing this alternative just to show that your logic is correct except for the pass-by-reference bit. (Note that the collatz function doesn't return anything now, the answer is in the global variable).
ctr = 0
def collatz(num):
global ctr
if(num != 1):
ctr+=1
if(num%2==0):
collatz(num/2)
else:
collatz(num*3+1)
ctr = 0
collatz(9)
print(ctr)
Since Python doesn't have tail-call-optimization, your current recursive code will crash with a stack overflow if the collatz sequence is longer than 1000 steps (this is Pythons default stack limit). You can avoid this problem by using a loop instead of recursion. This also lets use get rid of that troublesome global variable. The final result is a bit more idiomatic Python, in my opinion:
def collats(num):
ctr = 0
while num != 1:
ctr += 1
if num % 2 == 0:
num = num/2
else:
num = 3*num + 1
return ctr
print(collatz(9))
If you want to stick with using recursive functions, its usually cleaner to avoid using mutable assignment like you are trying to do. Instead of functions being "subroutines" that modify state, make them into something closer to mathematical functions, which receive a value and return a result that depends only on the inputs. It can be much easier to reason about recursion if you do this. I will leave this as an exercise but the typical "skeleton" of a recursive function is to have an if statement that checks for the base case and the recursive cases:
def collatz(n):
if n == 1:
return 0
else if n % 2 == 0:
# tip: something involving collatz(n/2)
return #???
else:
# tip: something involving collatz(3*n+1)
return #???
The variable will return the final number of the collatz sequence starting from whatever number you put in. The collatz conjecture says this will always be 1

Calculate the sum of the digits of a number recursively in Python

I'm having troubles with a recursive function in Python. The objective is for the function to calculate the sum of the digits of a number recursively.
This is what I have so far -- I realise that this version isn't as succinct as it could be, but right now I'm just trying to understand why it isn't working as is:
total = 0 #global variable declaration
def digit_sum(n):
global total #to be able to update the same variable at every level of recursion
total += n % 10 #adding the last digit to the total
n //= 10 #removing the last digit of the number
if n < 10:
total += n
return total
else:
digit_sum(n)
print 'The return value of the function is: ', digit_sum(12345)
print 'The final value stored in total is: ', total
I obtain the following output:
The return value of the function is: None
The final value stored in total is: 15
My function is somewhat working, since the final value stored in the global variable total is correct, but printing the function output returns None instead of 15.
Could you please help me understand why?
Thank you.
Interesting problem, and an interesting solution! Let me debug with a more simple number - 421.
On first call, total is assigned the value 1 and n becomes 42. The else branch gets executed.
On second call, total gets value of 3 and n becomes 4. The if branch is executed and the value total = 7 is returned.
So, why are we seeing the None? Let's inspect the call-stack:
> digit_sum(n = 421)
> > digit_sum(n = 42) # call to digit_sum from inside digit_sum
> -< 7 # value returned by inner/second call
> None
As you can notice, the value being returned by the second call is received by the first call, but the first call doesn't return the value being returned by the second call, so that's why you are seeing None.
But why does't first call return the value being returned by the second call?
Because of this line:
else:
digit_sum(n)
You are calling the function a second time, but you are not returning its return value.
Hope it helps! :)
The problem is that you didn't add a return statement in your else clause.
Adding 'return digit_sum(n)' should solve your problem:
if n < 10:
total += n
return total
else:
return digit_sum(n)
Example
When you have a recursive function (I'll take n! as example), calls are made until you reach a 'base case' (2 in n! and for you if n<10).
Let's take a look at factorial:
def fact(n):
if(n<=2):
return n
else:
return n*fact(n-1)
Without the return statement in else clause, if you ask for fact(4), this will also return none.
Here are the 'calls' with the return statement:
return (4*fact(3))
return (4*(3*fact(2)))
return (4*(3*(2)))
Which gives 24.
Here are those without:
(4*fact(3))
(4*(3*fact(2)))
(4*(3*(2)))
So the calculus is made, but nothing is returned.
I hope this will help you to understand.
NB: Here is a factorial implementation where recursivity is explained.
my solution is
def f(n):
if n/10 == 0:
return n
return n%10 + f(n/10)
output:
f(12345) = 15

Categories

Resources