Python Basics (Functions)

Why use functions?     
Solve the problem of code reuse
Unified maintenance The organization structure of the program is clear and the
readability
is
strong The form of
an empty function

function:
def function name (arg1, arg2, arg3): #arg parameter optional
'description information'
function body
return 0 #return value

definition parameterized function
def bar(x,y): with parameters in parentheses Called the parameterized function
print(x) The parameters of the
print(y)

function:
def foo(x,y): #Formal parameters: in the function definition stage, the parameters defined in parentheses
foo (1, 2) #Actual parameters: in In the function call phase, the parameters defined in parentheses are
analyzed from the perspective of actual parameters:
1. Pass the value by position eg: foo(1,2)
2. Pass the value by keyword eg:foo(x=1,y=2)
3. Mixed use of positional value and keyword value (note: positional value must be in front of keyword value; only one value can be assigned to a formal parameter) eg: foo(1,y=2)
Analysis from the perspective of formal parameters: positional parameters must be passed by value. Default parameters must be placed after positional parameters 
def foo(*args):
def foo(x,*args,y=1):*args should be placed after positional parameters* args returns a tuple in the form
def foo(x,**kwargs): **kwargs returns a dictionary in the form
def foo(x,*args,**kwargs):

defines a parameterless function
def foo() :
'foo function'
print('from the foo')
print(foo.__doc__)

defines an empty function
def auth():


The calling statement of the pass function is in the form of: foo() #There are no parameters in the definition and no parameters in the call bar(1 ,2) #There are parameters in the definition, and the parameters need to be passed when calling. The expression is in the form: res=10*my_sum(1,2) The function call is used as a parameter of another function: print(my_sum(1,2)) def function(x ,y): # Ternary operator res=x if x > y else y return res hehe = function (1, 2) print (hehe) The return value of the function can be any type without return--->None













return 1--->1 returns this value
return 1,2,3--->(1,2,3) returns a tuple

Guess you like

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