Understanding functions in Python

//Encapsulate the code block that performs a certain function, which can be called repeatedly, and separate the code block from the main program, which can make the main program easier to understand

1. Format

def functionName(): //define(specify)
""" docstring (describes what this function does) """
code block

2. Formal and actual parameters

Formal parameter: The variable after the function name when the function is defined
Actual parameter: The information provided to the function when the function is called

3. Pass arguments


A.位置实参:形、实参顺序对应,可多次调用
B.关键字实参(命名参数):每个实参都是变量名和值关联,无需考虑顺序
C.默认值(缺省参数):若未指定实参则用形参中定义的默认值
D.不定长参数:
函数可以接受不定个数的参数传入
#函数调用时,传入的不定长参数会封装成元组
def function([format_args,] * args)
#函数调用时,传入的不定长参数封装成字典
#养老金、医疗、公积金
def any_num_dict(b_money,**proportion):
print(proportion)
e_money=b_money * proportion["e"]
m_money=b_money * proportion["m"]
a_money=b_money * proportion["a"]
return e_money,m_money,a_money
any_num_dict(10000,e=0.2,m=0.1,a=0.3) }
def function([format_args,]) ** args)
#形参既有位置、不定长和缺省的话传参时缺省要赋值!

4. Return value

//Process some data and return a / a set of values
​​A. Directly process each value in the function
{ #Use the function to implement the calculator through the list
def compute(x,y):
res_plus=x+y
res_minus=xy
res_ride =x*y
res_chu=x/y
return res-plus,res_minus,res_ride,res_chu //default return tuple
plus,minus,ride,chu=compute(10,5)
print(~) }

5. Pass arguments by default to make arguments programming optional

{ #Test the actual parameter by the middle name of the name optional
def get_formatted_name(first_name,last_name,middle_name=”):
"""Determine whether there is a middle name and return"""
if middle_name:
full_name=first_name+middle_name+last_name
else:
full_name=first_name+last_name
return full_name

No middle name test
name = get_formatted_name('Kevin','Mahone')
print(name)

with middle name test
name = get_formatted_name('Kevin','Mahone','nice')
print(name) }

6. Return the dictionary

def build_person(f_n,s_n):
"""Return a dictionary containing a person's information"""
person={'first_name':f_n,'second_name':s_n}
return person
print(build_person('Kevin','Mahone' ))

7. Combine function and while loop
{ # Greet customers in a formal way
def get_formatted_name(first_name, last_name):
"'connection name"'
full_name=first_name+last_name
return full_name

Begin while prompting the user to enter
while True:
print("Please tell me your name:\n")
print("(enter 'q' at any time to quit!)")

f_name=input("First name:\n")
if f_name == 'q':
    break
l_name=input("Last name:\n")
if l_name == 'q':
    break

formatted_name=get_formatted_name(f_name,l_name)
print("Hello,"+formatted_name+"!")
break   }

8. Pass the list

A. Pass the list to the function
B. Modify the list in the function
{
def print_models(unprinted_models,complete_models):
"'simulate each design printed and after printing each design, move to complete_models"'
while unprinted_models:
current_models=unprinted_models. pop()
complete_models.append(current_models)
def show_complete_models(complete_models):
"'Show all models that have been printed"'
for complete_model in complete_models:
print(complete_model)
unprited_models=['one','two','three',' four','five']
complete_models=[]
print_models(unprited_models,complete_models)
show_complete_models(complete_models) }
C. Forbidden function to modify the list
//In the actual parameter when calling the function: functionName(act_par1[:],act_par2) //Passed is a copy of the original list

9. Pass arguments

A. Pass any number of arguments
functionName( * formalParameter) //This formal parameter will be included no matter how many arguments are provided
B. Use positional arguments in combination with any number of arguments
//Any number of arguments will be accepted in the function definition The formal parameters are put at the end
[Pyhon matches the positional arguments and keyword arguments first, and finally collects the remaining arguments into the last formal parameter]
C. Use any number of keyword arguments

10. Functions are stored in modules

//The function is stored in a separate file of the module, which can hide the details of the code, focus on high-level logic, and reuse the function in different programs
[module is the extension .py file]
A. Format:
– import the module, use the module Functions in:
import moduleName
moduleName.functionName()
– import all functions in the module
from moduleName import *
– import specific functions:
from moduleName import functionName
– separate function names with commas, any number of functions can be imported:
from moduleName import functionName0, functionName1, functionName2
B. Use as to assign aliases
– assign aliases to modules:
import moduleName as mN
– assign aliases to functions:
from moduleName import functionName as fN

11. Function Writing Guidelines

// Details to keep in mind when writing functions:
- Canonical ("_" split) specifying function descriptive names
- Each function should have a descriptive comment, immediately following the function definition, in the format of a
docstring - PEP8 It is recommended that the code length should not exceed 79 characters, if there are too many formal parameters:

def functionName(
paramter_0,paramter_1,paramter_2,
paramter_3,paramter_4,paramter_5 ):
function body

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325937624&siteId=291194637