用户可以为函数指定返回值,返回值可以是任意的数据类型,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))
本文通过两个示例介绍了Python中return关键字的使用。第一个例子展示了如何根据条件返回布尔值,第二个例子则是一个统计字符串中包含特定字符单词的函数,该函数返回一个列表。这些示例突显了函数在处理逻辑和返回不同数据类型方面的灵活性。
1757

被折叠的 条评论
为什么被折叠?



