我正在学习python,我只是想知道我是否有办法编写一个类似的代码:
def f(x):
if x>1:
return(x)
else:
# don't return anything
Run Code Online (Sandbox Code Playgroud)
我问的是代码的其他部分.如果x<=1返回None是不可接受的,我不需要返回任何东西.
Blc*_*ght 27
在Python中没有"什么都不返回"这样的东西.每个函数都返回一些值(除非它引发异常).如果没有使用显式return语句,Python会将其视为返回None.
所以,你需要考虑什么是最适合你的功能.您应该返回None(或其他一些标记值)并向您的调用代码添加适当的逻辑来检测它,或者您应该引发一个异常(调用代码可以捕获,如果它想要).
Sin*_*int 12
要从字面上返回 'nothing' 使用pass,它基本上返回值 None 如果放在函数中(函数必须返回一个值,那么为什么不是 'nothing')。不过,您可以明确地和您return None自己这样做。
所以要么:
if x>1:
return(x)
else:
pass
Run Code Online (Sandbox Code Playgroud)
或者
if x>1:
return(x)
else:
return None
Run Code Online (Sandbox Code Playgroud)
会做的伎俩。
小智 5
没有什么比不返回任何内容更好的了,但是您想要做的事情可以通过使用空return语句来完成。它返回一个None.
您可以看到下面的示例:
if 'account' in command:
account()
def account():
talkToMe('We need to verify your identity for this. Please cooperate.')
talkToMe('May I know your account number please?')
acc_number = myCommand()
talkToMe('you said your account number is '+acc_number+'. Is it right?')
confirmation = myCommand()
if confirmation!='yes' or 'correct' or 'yeah':
talkToMe('Let\'s try again!')
account()
else:
talkToMe('please wait!')
return
Run Code Online (Sandbox Code Playgroud)
这不会向调用函数返回任何内容,但会停止执行并到达调用函数。
| 归档时间: |
|
| 查看次数: |
32798 次 |
| 最近记录: |