table of Contents
Function Section
Function system
- What is the function
- Why use function
- Classification function
- grammar
- There are parameters defined function
- Defined parameter-free function
- Define an empty function, and function space scenario
- call function
- How to call a function
- Function's return value
- Application parameters as a function of: and parameter arguments, the position parameter and the position of arguments, argument a keyword, the default parameter, * args, ** kwargs
What is the function
Function is the programming language packages of various tools, encountered when the long view requires the use of a direct call to
Why use the function
When the program code is too long, if the write together, there will be a lengthy procedure, the program may expand poor maintainability readable program, then the need to split the functionality of the sub-function
How to use the function
- Define function, after calling
- Defined Functions
def 函数名 (param1.param2..):
code 1
code 2
code 3
return 返回值
- call function
函数名(param1,param2...)
- Functions registration function
def register():
usename = input('usename:').strip()
pwd = input('password':).strip()
with open('1.txt','a',encoding = 'utf8') as fa:
fa.writea(f'{usenamea}:{pwd}\n')
fa.flush
register()
register()
register()
- Function login feature
def login():
usename = input('usename:').strip()
pwd = input('password':).strip()
with open('1.txt','rt',encoding = 'utf8') as fr:
for use_info in fr:
user_info = use_info.strip('\n').split(:)
if usename == suer_info[0] and pwd == user_info[1]:
print('login sucessful')
else:
print('账号密码错误')
login()
- Function definition stage
def func():
bar()
print('*' * 10)
- Function call stage
def bar():
print('from bar')
def foo():
print('from foo')
bar()
foo()
def foo():
print('from foo')
bar()
def bar():
print('from bar')
foo() # 函数调用
Functions defined in three ways
No-argument function
When you define a function parameter is a function of receiving an external body mass is worth a medium, in fact, a variable name
Function parameters is not within the parentheses, a function is called without parameter it should be noted that: the definition with no arguments, when calling means need not pass parameters, if the function code logic bodies need to rely on an external incoming values must be defined as no-argument function
def func():
print('hello word')
func()
There are function parameters
There are parameters in the function definition stage brackets, known to have a reference function, note that: There is a reference when defining must be passed parameters means that calling
If the code body functions rely incoming external value, there must be defined as a function of parameters
def sum_self(x,y):
res = x+y
print(res)
sum_self(2,3)
Empty function
When you only need to implement a feature, but do not know how to use time code to achieve, you can temporarily use the empty function to skip, go for other functions
def func():
pass
Function's return value
What is the return value
After a series of the code within the function of logic judgment result will be processed
def func():
name = 'nick'
return name
name = func()
print name # 返回函数值
Why should there be a return value
There is now a need to compare two people's monthly salary, then people get a larger monthly salary
If you need to get the result of the processing function for further processing in the program, you will need to function must have a return value
have to be aware of is:
- return is a sign of the end of the function, the function can have multiple return values, as long as the execution to return, the function will stop
- return function can return any type of data
- unrestricted return of a return value, which can return multiple values separated by commas (when the return value is plural, is output in the form of tuples)
def max_self(salary_x, salary_y)
if salary_x > salary_y:
return salary_x
else:
return salart_y
max_salart = max_self(2000,3000)
print(max_salary * 12) # return 360000
def func():
name = 'nick'
age = 19
hobby_list = ['read','run']
return name,age,hobby_list
name,age,hobby_list = func()
print(f'name,age,hobby_list:{name,age,hobby_list}')
# name,age,hobby_list:('nick',19,['read','run'])
Call functions
What is the function call
When the function at 函数名()
the time of the form, the code body will execute the function, known or encountered return all the code after executing the function body end
Function has finished running all the code, if the function body do not write return, it will return None
def foo:
pass
print(foo())
Why call the function
Using the function in the function, simplified procedure
Three types of function calls
def max_self(x,y):
if x > y:
return x
else:
return y
max_self(1,2)
res = max_self(1,2) *12
max_self(max_self(2000,3000),4000)
Application function parameters
Katachisan
Parameters defined in parentheses function definition stage, called the formal parameters, parameter referred to, is essentially the variable name
def func(x,y):
print(x)
print(y)
Arguments
Passed in the function call stage parentheses parameters, known as actual parameters, referred to the argument, in essence, is the value of the variable
func(1,2)
Positional parameters
Location parameter
In the definition phase function according to the parameter defined sequentially from left to right, called the position parameter
def func(x,y)
print(x)
print(y)
Features: parameter defined according to the position, must be transmitted value, not a one more not less
Argument position
Function call stage, in order from left to right in turn defined arguments, argument called
func(1,2)
Features: sequentially pass the reference value according to the position corresponding to the shape
Keyword arguments
When calling the function, in the form of key = value passed as a parameter to the specified value, referred to as keyword parameters
func (y = 2, x = 1)
Features: You can break the limit position, but still for the specified parameter assignment
note:
- You can mix position arguments and keyword arguments, but the location argument must be key arguments in the left
- Position and can be mixed arguments keyword arguments, but can not repeat the assignment for a parameter
func(x, y=2)
func(y=2,x)
func(x,x=1)
The default parameter
During the definition phase, it has been assigned
def func(x,y=10):
print(x)
print(y)
func(2)
Features: During the definition phase has already been assigned, which means you can not assign a value when calling
note:
- Parameter in the default position of the left parameter
- The default parameter values assigned only once in the definition phase, which means that the default value of the parameter in the function definition phase has been fixed
m = 10
def foo(x = m)
print(x)
m = 111
foo()
- The default value of the parameter should normally be immutable
def register(name,hobby,hobby_list = []):
hobby_list.append(hobby)
print(f'{name}prefer{hobby}')
print(f'{name}prefer{hobby_list}')
register('nick', 'read')
register('tank','zuipiao')
register('jsaon', 'piao')
def register(name,hobby,hobby_list = None):
if hobby_list is None:
hobby_list = []
hobby_list.append(hobby)
print(f'{name}prefer{hobby}')
print(f'{name}prefer{hobby_list}')
register('nick', 'read')
register('tank','zuipiao')
register('jsaon', 'piao')
to sum up
Arguments applications depends on personal habits
== shape parameters of the application:
- Recall value == Like most cases, the parameter should be defined as a location parameter ==
- == recall value in most cases the same, it should define the parameters to the default parameter ==