Stored (and Reused) Steps
def ..():
...
return ...
用于存储之后可能还要输出很多次的内容,定义一个函数可以简化后续的输入
比如
def thing(): #构造一个thing函数
print('hello') #定义thing函数为输出hello
thing() #再次输入该函数即可invoke(调用)
# 执行后的output为hello
Built-in Function
max() #取大,如果是字符串则去字母顺序最大
#type conversion
int()
float()
str()
Fruitful function
有return values的函数是Fruitful
call/invoke
def了函数之后,还要call/invoke(调用),才会被使用,否则只是存储了这个定义
arguments
用函数处理的内容,即输入进函数括号内的东西,给函数取的不同的值
multiple arguments,用逗号隔开,可输入多个
parameters
用来命名函数处理的内容,是个变量,是placeholder(占位符)
multiple parameters
return values
1.运行到return这一行,则不能进入下一行,标志着调用的结束
2.作为参数,停止函数的执行,return residual value(当标明return了什么具体的值),类似于print
return 1
# 输出为1
#没有return或只有return,输出为none
Void(non-fruitful) Function
没有return values是Void
To function or not to function
不要着急用function,有天你觉得coding很麻烦很重复,这个时候想要创造function再用
一些建议:
- Organize your code into “paragraphs” - capture a complete thought and " name it"
尽量让代码形成paragraphs,命名它 - Don’t repeat yourself - make it work once and then reuse it
减少重复劳作,尽量做一次之后可以重复使用 - lf something gets too long or complex, break it up into logical chunks and put those chunks in functions
太复杂太长的code可以整理成几个逻辑块,变成几个函数 - Make a library of common stuff that you do over and orperhaps share this with your friends
总结自己常用的function,分享出来