是否有类似于 MATLAB 中'return'函数的 Python 命令?



Python中是否有函数可以控件返回到调用脚本或函数,类似于MATLAB中的函数返回

Python中的函数exit((或quit((也做同样的事情吗?

def absolute_value(num):
"""This function returns the absolute
value of the entered number"""
if num >= 0:
# Return to the invoking script without any return value
else:
# Do task A
# Do task B

print(absolute_value(2))
print(absolute_value(-4))

是的,Python方法可以return一个值,类似于MATLAB中的例子。

所以,这个MATLAB代码

function idx = findSqrRootIndex(target, arrayToSearch)
idx = NaN;
if target < 0
return
end
for idx = 1:length(arrayToSearch)
if arrayToSearch(idx) == sqrt(target)
return
end
end

可以有效地用Python写成-

import math
def find_sqr_root_index(target, array_to_search):
if target < 0:
return # Same as return None
# Indexing starts at 0, unlike MATLAB
for idx in range(len(array_to_search)):
if array_to_search[idx] == math.sqrt(target):
return idx
a = [3, 7, 28, 14, 42, 9, 0]
b = 81
val = find_sqr_root_index(b, a)
print(val) # 5 (5 would mean the 6th element)

Python代码更改了方法和变量的名称,以符合Python的命名约定。

只需添加,就可以像在MATLAB中一样使用返回,而不需要任何的返回值

Python的返回语句。return语句用于结束函数调用的执行,并将结果(return关键字后面的表达式值("返回"给调用方。返回语句之后的语句不会执行。这相当于MATLAB的返回

def my_func(a):
# Some code
if a == 5:
return # This is valid too, equivalent 
# to quit the function and go 
# to the invoking script

最新更新