Loading

Python函数之def定义函数

链接

想研究Python函数?看这里
函数怎样取名?看这里
有参数的函数还可以怎么传参?看这里

一、无参数函数

结构

def <函数名>(): # 强制要求
	<函数体> # 可省略
	return <返回值> # 可省略

程序举例

用函数的Hello world程序:

# prints 'Hello World\nDone'
# Author: GoodCoder666
def getHelloWorldString():
	return 'Hello World'
def print_hello_world():
	print(getHelloWorldString())
print_hello_world()
print('Done')
# 输出:
# Hello World
# Done

程序流程

flowchat st=>start: 开始,调用print_hello_world() e=>end: 结束 get_str_call=>operation: print_hello_world()调用getHelloWorldString() return_str=>operation: getHelloWorldString()返回 'Hello world' print_hi=>inputoutput: 回到print_hello_world(),输出Hello world done=>inputoutput: 回到主程序,输出Done st->get_str_call->return_str->print_hi->done->e

二、有参数函数

补充知识

参数 (parameter):给函数的值,在函数中相当于变量:

def param_test(a, b):
	a, b = b, a
	print(a, b)
param_test(5, 6) # 输出:6 5

以上程序等同于:

def param_test():
	a, b = 5, 6
	#-----以下部分相同-----#
	a, b = b, a
	print(a, b)
param_test() # 输出:6 5

结构

def <函数名>(<参数列表>): # 强制要求
	<函数体> # 可省略
	return <返回值> # 可省略

其中,参数列表中的参数用,隔开,例如a, bc(如果只有一个参数直接写)

程序举例

# prints 'Hi, {name}!'
# Author: GoodCoder666
def get_greet_str(name):
	return 'Hi, ' + name + '!'

def greet(name):
	print(get_greet_str(name))

greet(input("What's your name? "))
print('Done')
# 输入: GoodCoder666
# 输出
# Hi, GoodCoder666!
# Done

程序流程

flowchat st=>start: 开始,调用input("What's your name?") e=>end: 结束 call_greet=>operation: input返回用户名,调用greet(<用户名>) call_get_greet_str=>operation: greet调用get_greet_str(<用户名>) print_hi=>inputoutput: 回到get_greet_str,输出get_greet_str的返回值 done=>inputoutput: 回到主程序,输出Done st->call_greet->call_get_greet_str->print_hi->done->e

函数也是对象

一个函数也是一个对象。

证明

先定义两个函数:

def a(a, b):
	return a + b
def b():
	return a(1, 2)
项目 是否支持/存在 证明
赋值 Y c = a可执行;执行后c可被调用
属性 Y 执行type(a),返回class <'function'>
类型 Y
posted @ 2020-04-21 13:22  GoodCoder666  阅读(42)  评论(0)    收藏  举报