Def definition function of Python function

link

Want to study Pythonfunctions? See here.
How is the function named? Look here.
How can a function with parameters pass parameters? look here

One, no parameter function

structure

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

Program example

Hello worldProgram with function :

# 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

Procedure flow chart

Created with Raphaël 2.2.0 开始,调用print_hello_world() print_hello_world()调用getHelloWorldString() getHelloWorldString()返回 'Hello world' 回到print_hello_world(),输出Hello world 回到主程序,输出Done 结束

Second, a function with parameters

Supplementary knowledge

Parameter ( parameter ): The value given to the function, which is equivalent to a variable in the function:

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

The above procedure is equivalent to:

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

structure

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

Among them, the parameters in the parameter list are ,separated by, for example a, b, c(If there is only one parameter, write directly)

Program example

# 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

Procedure flow chart

Created with Raphaël 2.2.0 开始,调用input("What's your name?") input返回用户名,调用greet(<用户名>) greet调用get_greet_str(<用户名>) 回到get_greet_str,输出get_greet_str的返回值 回到主程序,输出Done 结束

Functions are also objects

A function is also an object.

prove

First define two functions:

def a(a, b):
	return a + b
def b():
	return a(1, 2)
project Support/exist prove
Assignment AND c = aExecutable; ccan be called after execution
Attributes AND Execute type(a), returnclass <'function'>
Types of AND

Guess you like

Origin blog.csdn.net/write_1m_lines/article/details/105641275
Recommended