why does the following code returns none:
j = 22
def test(j):
if j > 0:
print('j>0')
else:
print('j<0')
Output:
j>0
None
A function in Python always has a return value, even if you do not use a return statement, defaulting to None
Because the test function doesn't return a value, it ends up returning the object None. that's why it ended up printing None Since you do not have a return value specified
you may not use print in your function, but return a string instead
def test(j):
if j > 0:
return 'j>0'
else:
return 'j<0'
then call it like this: print it when calling the function
print(test(22))
see answer's here for more detail
Related
This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 25 days ago.
def myfun1(count):
count += 1
if count == 10:
return count
print(count)
myfun1(count)
if __name__ == '__main__':
print(myfun1(0))
I want to return the count and terminate the recursion when count == 10.
The above code returns None when count == 10. Could someone please elaborate?
Instruction myfun1(count) performs a recursive call but you don't do anything of the value returned by this call. You need to return a value when you reach the end of your function. Otherwise, when the end of the function is reached, you have an implicit return None statement.
So if you want to return the result of your recursive call, do something like that:
def myfun1(count):
count += 1
if count == 10:
return count
print(count)
result = myfun1(count)
return result
if __name__ == '__main__':
print(myfun1(0))
Generally speaking when a function (recursive or not) is supposed to return something that it computed, make sure that it ends with a return statement.
First you need Else to return a different value in return, instead you will always return 10 in your recursion
def myFun1(count):
count += 1
if count == 10:
return count
else:
return count
and you have refactore some points of your function to make the recursion, call it again
def myFun1(count):
count += 1
if count == 10:
return count
else:
count_res = myFun1(count)
return count_res
and you have just call the function
if name == 'main':
print(myFun1(0))
n = int(input())
def reverse(num):
while num > 0:
return f"{num}{reverse(num - 1)}"
result = reverse(n)
print(result)
I have some code lines as above. (Incase Input n = 5)It prints "54321None" instead of "54321" as I expected.
Please help me
The last iteration will always be a 0. If you just call reverse(0) it will return None, so that is the problem.
Without rewriting too much code the 'simple' solution could be:
return f"{num}{reverse(num-1)if num-1 != 0 else ''}"
This only executes the reverse function if the variable you pass into reverse is not 0. Otherwise it will return Nothing.
I just saw the following Python code, and I'm a bit confused by the first return. Does it return None by default? Is it equivalent to return(None)? If the first return is executed, will the function inner() automatically end there and the second return be left alone?
def smart_check(f):
def inner(a,b):
if b==0:
print("illegit: b =", b)
return # the first return
return(f(a,b))
return(inner)
#smart_check
def divide(a,b):
return(a/b)
Does it return None by default? Is it equivalent to return(None)
Yes, see docs: If an expression list is present, it is evaluated, else None is
substituted.
If the first return is executed, will the function inner()
automatically end there and the second return be left alone?
Yes
If you don't want to return anything you can even drop the return statement completely:
def smart_check(f):
def inner(a,b):
if b != 0:
return f(a,b)
print("illegit: b =", b)
return(inner)
As print doesn't return anything you could even rewrite this function as
def smart_check(f):
def inner(a,b):
return f(a,b) if b!=0 else print("illegit: b =", b)
return(inner)
The finally block in this code doesn't execute at all.
I have wrote this code to prevent assigning a None value to the current object, so I came up with an idea to use finally and assign this object with the previous state, but when I execute it the finally block doesn't execute at all (I have added a print statement to see if it's executed and it's not).
def __idiv__(self, other):
try:
if other is None:
raise ValueError('The second number is None')
if not isinstance(other, Complex):
other = Complex(other)
den = other * other.con()
num = self * other.con()
re = num.re / den.re
im = num.im / den.re
return Complex(re, im)
except (ZeroDivisionError, ValueError) as err:
print(colored('{}: {}'.format(err.__class__.__name__, err), 'red'))
finally:
print('-'*80)
return Complex(self.re, self.im)
When I call this method I just get this without the output of print statement in finally block:
ZeroDivisionError: float division by zero
Am I doing something wrong? There was no errors running the program. This should output a boolean value, but when I run it there is no return value. The program lets the user to enter a number, but then the program doesn't return anything.
def main():
num = int(input("Enter a number:"))
isPrime(num)
def isPrime(num):
if num < 2:
return False
elif num == 2:
return True
else:
for counter in range(2, num):
if num % counter == 0:
return True
return False
main()
Do you mean to print isPrime (num)?
No, the return statement itself will not print to the console. The print statement does that.
"return" only returns that value from the function, it does not display anything to the screen. You could assign the value that is being returned to a variable, but if it is not assigned or used, it is lost. If you wanted it to actually be displayed, you could do
print(isPrime(num))
which will then print out the resulting boolean to the console, or assign the returned value to a variable for later use.
You may do like this
result = isPrime(num)
print(result)