用户可以为函数指定返回值,返回值可以是任意的数据类型,return[expression] 语句用于退出函数,将表达式值作为返回值传递给调用方。不带参数值的 return 语句返回 None。
例 6-11 return 关键字的应用:
>>> def compare(arg1,arg2):
'''比较两个参数大小'''
result = arg1>arg2
return result
>>> btest = compare(10,9.99)
>>> print("函数的返回值:",btest)
函数的返回值: True
例 6-12 统计字符串中含有 ‘e’ 的单词:
#ex0612.py
def findwords(sentence):
'''统计参数中含有字符 e 的单词,保存到列表中,并返回'''
result = []
words = sentence.split()
for word in words:
if word.find("e") != -1:#find()函数如果包含子字符串返回开始的索引值,否则返回-1。
result.append(word)
return result
ss = "You may need to manually configure the HiDPI " \
"mode to prevent UI scaling issues. See the " \
"troubleshooting guide. Do not show again."
print(findwords(ss))