Python custom function definition arguments call code parsing
- 2020-06-19 10:56:41
- OfStack
Functions improve application modularity and code reuse. Python provides many built-in functions, such as print(). User-defined functions can also be created.
The function definitions
Simple rules for function definitions:
The function code block begins with the def keyword, followed by the function identifier name and parentheses (), and any arguments and arguments passed in must be placed between parentheses
Function content begins with a colon and is indented
If there is a return value, Return[expression] ends the function; The expression without return is equivalent to returning None
Functions typically use three single quotes ""... To annotate the function; Function body content cannot be empty, pass can be used to represent empty statement; Here are some simple function examples:
''' some basic functions '''
def func1(): # The function takes no arguments
print("func1") # There is no return value
func1() # A function call
def func2():
return("func2") # return string "func2"
print(func2())
def func3(a,b): # Two parameters need to be passed
print("a+b = %d" %(a+b)) # print Expression, none return
func3(3,4)
def func4(a,b): # Two parameters need to be passed
return (a+b) # return a+b The value of the
print(func4(4,3))
A function call
Define a function that gives the function a name, specifies the parameters that the function contains, and the code block structure.
Once the basic structure of this function is complete, you can execute it either via another function call or directly from the Python prompt.
In the above example, func1() is a call to a parameterless function; func3(3,4) is a call to a function with arguments
Drill down on function definitions
Default parameter value
The most common form is to specify a default value for one or more parameters. Parameters with default values are not passed in. Refer to the following examples:
''' advanced: Simple query box '''
def ask_ok(hint, retries=4, complaint='Yes or no, please!'): # only hint It has to be passed in, retries and complaint Both have default values
while True:
u = input(hint)
if u in ('y','ye','yes'): # in The use of; If the user answers in ('y','ye','yes') return True
return True
if u in ('n','no','nop','nope'): # If the user answers in ('n','no','nop','nope') return False
return False
retries = retries -1 # If the user input is not listed previously, you can retry, retry times -1
if retries <= 0 : # If the number of retries is exceeded, raise The custom Error
raise IOError('refusenik user')
print(complaint) # Prompt if user input is not listed previously complaint information
result1 = ask_ok("Yes or No?") # Only the necessary parameter values are given hint , you can try input 'y' 'no' And so on; Enter other such as 'x' More than 4 time
print(result1) # To view return The value of the
# result2 = ask_ok("Yes or No?",2) # given retries=2 , try to enter other such as 'x' More than 2 time
# result3 = ask_ok("Yes or No?",'Y or N?') # Do not omit the first 2 If you try to enter other such as 'x' And complains
# result4 = ask_ok("Yes or No?",3,'Y or N?') # Given all the parameters, try the input 'y' 'no' And so on; Enter other such as 'x' More than 3 time
# print(result4)
Note: Default values are resolved in the function definition scope, as shown below
''' Default values are resolved in the function definition scope '''
i = 5
def print_i(var=i):
print(var)
i = 6
print_i() # The output is 5
Important: Default values are assigned only once. This makes a difference when the default value is a mutable object, such as a list, dictionary, or instance of most classes. For example, a function accumulates arguments passed to it during subsequent calls.
''' Default values are only assigned 1 Times. This makes a difference when the default value is a mutable object, such as a list, dictionary, or instance of most classes.
The function accumulates arguments passed to it during subsequent calls.
'''
def append_L(a,L=[]): # Must pass arguments a . L No, it doesn't list , the default is empty
L.append(a)
return L
print(append_L(1)) # Parameters are given a=1, At this time L Has become [1]
print(append_L(2)) # The output [1,2]
print(append_L(3)) # The output [1,2,3]
''' L By default, changes are made L Instead of a cumulative value, the function can be defined as follows '''
def change_L(a,L=None):
if L is None:
L = []
L.append(a)
return L
print(change_L(1)) # Parameters are given a=1, L for None
print(change_L(2)) # Parameters are given a=2, L for None The output [2]
print(change_L(3,[0])) # Parameters are given a=1, L=[0] The output [0,3]
Keyword parameter
In the above example, the arguments given by the calling function are in the order defined. Functions can also be called in the form of keyword functions, as shown in the following example:
def add(a,b):
return (a+b)
print(add(b=9,a=2)) # Keyword parameter definition b=9 , a=2 It has nothing to do with the order of transmission
# print(add(b=9,2)) # complains
Variable parameter list
A function can be called with a variable number of (rarely used) arguments wrapped in a tuple. Before these variable Numbers of parameters, there can be zero to more than one common parameter.
A variable parameter is represented by adding * before its parameter name, such as *args; See the following example:
def join_bysep(*strs,sep): # strs Can be multiple parameters
return sep.join(strs) # String concatenation function sep.join(str)
print(join_bysep("red","blue","green",sep=" "))
print(join_bysep("red","blue",sep=","))
print(join_bysep("red",sep=","))
print(join_bysep(sep=",")) # There is no strs Announced, as 1 Empty string
conclusion
This is the Python custom function definition, parameters, call code parsing all content, hope to help you. Interested friends can continue to refer to other related topics in this site, if there is any deficiency, welcome to comment out. Thank you for your support!