整个专栏皆为《笨办法学python3》的学习内容,只是在书本的内容上根据本人的学习进行的记录,方便之后的回顾。
def function_name(in_put):
content
return output
这里的input和output可以是打包后的东西,打包解包让函数看起来更加简洁。比如:
def function_name(*in_put):
input1,input2=in_put
content
return output
python中的*和**,能够让函数支持任意数量的参数。
调用函数b=function_name(a)的过程是:输入一个列表a➡赋值in_put=a➡对in_put进行解包,并进行函数中的其他操作得到output➡b=output。此时便得到了调用函数的输出内容b,因为b是一个列表,所以在使用时也可以根据需要解包使用:c,d=b,也可以使用“{}”.format()形式。
方法一:通过函数名在脚本中直接引用,例如之前的b=function_name(a)
方法二:在shell中运行python,可以引入已经写好的函数脚本:import ex23 ,之后在需要的时候运用函数:ex23.function_name(input)
另外,通过return可以返回到其他函数,将多个函数的功能进行联动,其中也包括返回本函数,这样在符合条件的情况下,函数会不断的自我循环,这在有些时候可以避免另外添加循环语句的冗余。举例:
案例1
def break_words(stuff):
"""This function will break up words for us."""
words=stuff.split(' ')#split() 通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则分隔 num+1 个子字符串
return words
def sort_words(words):
"""Sorts the words."""
return sorted(words)#排序,对可迭代对象进行排序
def sort_setence(sentence):
"""Takes in a full sentence and returns the sorted words."""
words=break_words(sentence)
return sort_words(words)
案例2
def main(language_file,encoding,errors):
line=language_file.readline()
if line:
print_line(line,encoding,errors)
return main(language_file,encoding,errors)