Content introduction:
- Basic concepts of functions and modules
- Code reuse using functions
- Common built-in modules and functions in Python
- Custom functions and calls between functions
- Parameters and return values in functions
function
-
A function is a group of statements that are grouped together to complete an operation
-
Benefits of using functions
- You can save the pain of writing repetitive code
- Coding can be organized and simplified
- Improve code readability
-
be careful
if__name__=="__main__": # Equivalent to Python simulator entry
Function classification
- Built in functions: provided by Python standard library
- User defined function
- No parameters, no return value
- Without parameters, with return value
- With parameters and no return value
- With parameter and return value
Common built-in functions
- Mathematical function
- Type conversion function
- math module
Custom function
-
Function definition: it is composed of function name, formal parameters and function body
def <Function name>(<parameter list>): <Function body> return <Return value list>
# User defined interval summation function def get_sum(start, end): # The parameters passed into the function are formal parameters """ Returns the cumulative sum of a given integer interval :param start: Starting value :param end: End value :return: Returns the cumulative sum """ if start > end: start, end = end, start result = 0 for var in range(start, end + 1): result += var return result #Leave two blank lines at the end of the custom function
Formal and argument
-
For the detailed introduction of formal parameters and arguments, you can click the link to view the parameter introduction of C language. The properties are the same
https://blog.csdn.net/weixin_46161549/article/details/108409620
-
Parameter passing in Python
1. When passing parameters, what is actually passed is an object (shared parameter)
2. Shared parameter passing: refers to the copy of each reference of each formal parameter of the function (copy of memory address)
3. To put it simply, a formal parameter is an alias of an argument in Python
Positional parameters and named keyword parameters
-
The arguments of the function are passed as positional parameters and named keyword parameters
def print_words(words, count): for var in range(count): print(words)
-
When using positional parameters, the parameters are required to be passed in the order they are in the function header
words = "I'm a monster. I'm carefree and free. I kill people without blinking an eye and eat people without salt" print_words(words, 10) # The order of parameter passing during call is consistent with the order defined in the function header print_words(10, words) # The order of parameter passing during the call is inconsistent with the order defined in the function header
-
When using named keyword parameters, the order of parameters can be arbitrary
words = "I'm a monster. I'm carefree and free. I kill people without blinking an eye and eat people without salt" print_words(count=5, words=words) print_words(words=words, count=5)
be careful:
1. Positional parameters and named keyword parameters can be mixed
2. When mixed, the positional parameter cannot appear after any named keyword parameter# Named keyword parameters -- use the * separator to distinguish position parameters from keyword parameters def print_info(name, age, *, country, job, nick_name): print("full name:", name, "Age:", age, "country:", country, "occupation:", job, "Nickname?", nick_name) print_info("Luo Ji", 25, job="Facing the wall", country="China", nick_name="Dark forest law")
-
demon
def print_words(words, count): """ When defining, the position of the parameter is fixed, so it is called position parameter :param words: :param count: :return: """ for var in range(count): print(words) # Call with position parameter. The position of the parameter is fixed and cannot be changed words1 = "I'm a monster, free and at ease!" count1 = 1 print_words(words1, count1) # The calling order of the argument is consistent with the definition order of the function header -- the calling mode of the position parameter words2 = "When you decide to change, the world will make way for you!" count2 = 1 print_words(count=count2, words=words2) # Call with named keyword parameters
Operation results
Keyword parameters
-
demon
def print_info(name, age, **keywords): print("full name:", name, "\n Age:", age) # By traversing the keywords dictionary parameters, you can obtain the specific parameters and corresponding values passed to the function for key in keywords: # Traverse the keys in the dictionary print(key, ": ", keywords[key]) print_info(name="A firefly", age=25, chinese="Blue space number", nick_name = "What suits you is the best!")
-
be careful:
Writing sequence of parameter combination: position parameter - > default parameter - > variable len gt h parameter - > keyword parameter - > named keyword parameter
Parameter transfer mechanism
- After the parameter is passed into the calling function, a new address space will be opened up
Pass parameters and return lists
-
Parameters cannot be modified inside a function
def do_add(lst): for item in lst: item += 10 lst = [x for x in range(10)] do_add(lst) print(lst) Output result:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
-
Parameters can be modified inside the function
def do_add(lst): for i in range(len(lst)): lst[i] += 10 lst = [x for x in range(10)] do_add(lst) print(lst) Output result:[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
-
Pass parameters using list slices
List slicing is equivalent to generating a copy of the list
-def do_add(lst): for i in range(len(lst)): lst[i] += 10 lst = [x for x in range(10)] do_add(lst[0:10]) print(lst) # Output result: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Use the list slice to analyze the changes of function parameters and addresses
-
Do not use list slicing
def do_add(list): for i in range(len(list)): list[i] += 10 return list list_old = [x for x in range(10)] list_new = do_add(list_old) print("Original list:", list_old, id(list_old)) print("New list:", list_new, id(list_new)) Output result: Original list: [10, 11, 12, 13, 14, 15, 16, 17, 18, 19] 2358005608640 New list: [10, 11, 12, 13, 14, 15, 16, 17, 18, 19] 2358005608640
-
Use list slicing
def do_add(list): for i in range(len(list)): list[i] += 10 return list list_old = [x for x in range(10)] list_new = do_add(list_old[:]) print("Original list:", list_old, id(list_old)) print("New list:", list_new, id(list_new)) Output result: Original list: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 2279910220416 New list: [10, 11, 12, 13, 14, 15, 16, 17, 18, 19] 2279910274240
Modular code
-
Modularization can make the code easy to maintain and debug, and improve the reusability of the code
- You can put the definition of a function in a py file called a module
- The module file can be imported and reused by our program
-
Custom module
Block code# @function: custom module example # @Description: module name -- mymodule py # 1. Define constants # 2. Definition of function pi = 3.141592653 # PI def pow(num, n = 2): """ seek num of n Power :param num: :param n: n The default value for is 2 :return: """ result = 1 for i in range(n): result *= num return result def print_curr_module_name(): print("Current module name:", __name__)
Calling code
import mymodule print(mymodule.pow(2)) mymodule.print_curr_module_name() print("Current module name:", __name__)
Output results
Scope of variable
-
The scope of a variable refers to the scope in which the variable can be referenced in the program
Variables created outside of all functions are global variables that can be accessed by all functions
The scope of a local variable starts at the place where the variable is created and ends at the end of the function containing the variable