![](/img/trans.png)
[英]Return value of if/else recursive function incorrect but print value correct
[英]how to write return function correct way without print return value?
def function(n):
if n % 2 != 0:
print('weird')
elif n % 2 == 0 and n in range(2, 5):
print('not weird')
elif n % 2 == 0 and n in range(6, 20):
print('weird')
elif n % 2 == 0 and n > 20:
print('not weird')
return n
while True:
n = int(input('enter the number: '))
print(function(n))
OUTPUT:
enter the number: 4
not weird
4
上面的代码,我不想再打印返回号4,不代表返回号怎么写?
将print(function(n))
更改为function(n)
def function(n):
if n % 2 != 0:
print('weird')
elif n % 2 == 0 and n in range(2, 5):
print('not weird')
elif n % 2 == 0 and n in range(6, 20):
print('weird')
elif n % 2 == 0 and n > 20:
print('not weird')
return n
while True:
n = int(input('enter the number: '))
function(n)
我的意思是你可以像这样在最后删除打印功能
def function(n):
if n % 2 != 0:
print('weird')
elif n % 2 == 0 and n in range(2, 5):
print('not weird')
elif n % 2 == 0 and n in range(6, 20):
print('weird')
elif n % 2 == 0 and n > 20:
print('not weird')
return n
while True:
n = int(input('enter the number: '))
function(n)
您也可以只从 function 返回而不打印。
you can use it this way.. remove the return from the function statement and also remove the print when calling this function.. If you only remove the return but still call the function using print(func(n)) then the output would be就像是
enter the number: 4
not weird
None
也许这就是你要找的?
def function(n):
if n % 2 != 0:
print('weird')
elif n % 2 == 0 and n in range(2, 5):
print('not weird')
elif n % 2 == 0 and n in range(6, 20):
print('weird')
elif n % 2 == 0 and n > 20:
print('not weird')
while True:
n = int(input('enter the number: '))
function(n)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.