The first difficulty in Python learning - functions. People who learn in this place feel that there is nothing. If they have not learned, they will be dazed when learning. Don't panic. Learning programming is like this. Learn it first. From the perspective of God, stick to clock in. I write one article a day and you can learn one article two days.
Function is the first difficulty in Python
Background of function
Why does the concept of function appear in programming language? There are two purposes.
- During development, many projects are developed by teams. Code functions are written into functions one by one to facilitate maintenance. Everyone can also develop relatively independently and shorten the overall development time
- After the code is written into a function, the repeated function can be written only once, and can be called directly in other places, which facilitates the reuse of the code.
There is still no intuitive feeling to write these two purposes directly. You should feel the usage of functions in the code.
Function initial contact
I have been familiar with the concept of function since the beginning of this series of blogs. For example, print, which I learned in the first article, is a built-in function, similar to len, add and sorted. The greatest convenience when calling a function is that you can use the function to use the desired effect without knowing the specific implementation of the function.
Definition of function
The specific syntax format is as follows:
def Function name(Parameter 1[,Parameter 2,Parameter 3...]): Code block Code block return Return value
Like if statements and for statements, pay attention to code indentation when defining and using functions.
The function name must be unique and meaningful. Don't use a as the function name. You may forget what this function is used for in the future.
Parameter values, not required, can be set according to the requirements of the function. Each parameter value is separated by.
The returned value is optional. Multiple returned values can be separated by commas.
Notice the semicolon at the end of the first line
Function with no parameters and no return value
This content will demonstrate the convenience of using functions.
# Create a function def show(): print("I am a function with no parameters and no return value") print("hello world") show() show() show() show() show()
After the function is declared, it is called through the function name (). The code above has written show() five times, indicating that the function has been called five times.
If the above effect is not achieved through the function, you need to copy the code inside the function 5 times.
print("I am a function with no parameters and no return value") print("hello world") print("I am a function with no parameters and no return value") print("hello world") print("I am a function with no parameters and no return value") print("hello world") print("I am a function with no parameters and no return value") print("hello world") print("I am a function with no parameters and no return value") print("hello world")
It's OK to simply copy the code. If I want to change hello to hi now, I don't need to modify the five positions of the code without using the function, but only need to modify one code block in the function.
Parameter design of function
The above design is a parameterless function, but in practical application, there is rarely a parameterless function. More often, it is necessary to pass parameters to the function.
Pass a parameter
There are parameters in the function, and the code is as follows:
# Declare a function with one argument def show(name): print("The name passed in is:", name) show("Charlie") show("Big Charlie") show("Little Charlie")
The name in the parentheses is the parameter, which can be used directly in the internal code block of the function.
Pass multiple parameters
For multiple parameters, you only need to add several more parameters in the parentheses when the function is declared.
# Declare a function with multiple arguments def show(name, age): print("The name passed in is:", name, " Age is:", age) show("Charlie", 20) show("Big Charlie", 21) show("Little Charlie", 18)
Pay attention to the position of multiple parameters. If the sequence is wrong, it will lead to serious bugs. In the above code, Charlie will be passed to name and 20 will be passed to age.
Keyword parameter (parameter name = value)
This parameter is passed in the form of parameter name = value when calling the function. In fact, when passing one or more parameters above, you can also pass parameters in this way. For example, modify the code as follows.
# Declare a function with one argument def show(name): print("The name passed in is:", name) show(name="Charlie") # Declare a function with multiple arguments def show1(name, age): print("The name passed in is:", name, " Age is:", age) show1(name="Charlie", age=20)
When the function is called in this form, the position of the parameter is not important because the specific value of the parameter has been specified.
Parameter defaults
When defining a function, you can give a default value to the parameter. If you call the function without assigning a value to the parameter, the program will use the default value without reporting an error.
# Parameters without default values def show(name): print("The name passed in is:", name) show() # An error will be reported when calling this function # Parameters with default values def show(name="Charlie"): print("The name passed in is:", name) show() # There is no problem with this function call, even if no parameters are passed, the default value will be used
If a parameter has a default value, note that the parameter must be placed on the far right of the function parameter position, such as the following function definition.
def show(a,b,c,name="Charlie"): pass
Function return value
The return value of correspondence is optional. It can be written or not. When it is not written, there will also be a return value, which is None.
Return to None
If the function does not write a return value, that is, return, Python will automatically add a line of code return None to the function body. The return value of the function can be assigned to a variable. You can know the specific content of the return by printing the variable.
# Function with no return value def show(): print("Note that there is no return") ret = show() print(ret)
The value of ret obtained is None, indicating that there is no return value.
If you only write return, you will also return None. Note that the following code is correct.
# Function with no return value def show(): print("Note that there is no return") return ret = show() print(ret)
Returns a value
Functions often have return values, such as returning calculation results after executing a piece of calculation code.
# Define a subtraction function def sub(a, b): c = a - b return c # The parameters are 2 and 1, and the result is returned ret = sub(2, 1) print(ret)
Return multiple values
Using return to return function data, you can return multiple values at one time. The returned data can be separated by commas.
# Define a subtraction function def sub(a, b): c = a - b d = a + b f = a / b return c, d, f # The parameters are 2 and 1, and the result is returned ret = sub(2, 1) print(ret)
The result returned is a tuple (1, 3, 2.0).
Return to dictionary and list
The function can return variables of string type, which is the same as returning a value, except for the difference of specific data types. In addition to the above mentioned contents, the function can also return complex data, such as dictionary or list. If there is no special description, you only need to return the dictionary and list as ordinary data types, such as the following code.
def sub1(): return [1, 2, 3] def sub2(): return {"name": "Charlie", "loc": "CSDN"}
When calling a function, the argument is a list
The reason why the parameter is a list is explained separately is that the list is a little special, which also leads to the concept of global variables and local variables. Don't worry about learning 100% confused for the first time. If you have the skills of other programming languages, that's another matter.
The specific code is as follows. Pay attention to the problems.
names = ["aaa","bbb","ccc"] def change_list(one_names): # Modify the position of the passed in list index 0 as jjj one_names[0] = "jjj" # Function call, and pass name as a parameter into the function change_list(names) print(names)
The final output result is ['jjj ',' BBB ',' CCC ']. What does this mean? The names outside the function are modified by the function. The question is, will all variables outside the function be modified when passed inside the parameter? Try another integer.
score = 1 def change_list(one_score): one_score = 333 # Function call, and pass score as a parameter into the function change_list(score) print(score)
At this time, although the score is modified to 333 inside the function, the print outside the function is not modified, but it is still 1. Now the problem arises. Python is not treated equally. The modification of list variables in the function affects external variables, while integer variables are not affected.
We dig this hole first and fill it slowly later. Why is the list modified in the function and will be affected outside the function, involving the lower concepts of memory address space. First learn about local variables and global variables.
Local and global variables
This concept is very difficult to understand. Yes, if you understand it, you know a little at this stage.
When designing a function, it is sometimes necessary to control the use range of variables. If the use range of variables is within the function, this variable is called a local variable. Note that it is within the function. If a variable is used throughout the program, it is a global variable.
The above content is only the first contact. In the function part, let's simply get a concept and say it in our heart.
Global variables can be used in all functions
score = 1 def change_list(): # Output the global variable score, because this variable is declared outside the function and can be used by everyone print(score) change_list() # It can also be used outside the function print(score)
The above score is not declared inside the function, but it can also be accessed inside the function. The variable score outside the function is a global variable.
Local variables cannot be used outside functions and other functions
def change_list(): # Local variable score, this function can be used score = 1 print(score) change_list() # The local variable score cannot be used outside the function print(score) # Other functions cannot be used internally def show(): print(score)
If the local and global variable names are duplicate
In programming, it is easy to have duplicate names. This situation is more embarrassing, and the difficulty of beginners continues to increase.
score = 5555 def change_list(): # Local variable score, this function can be used score = 6666 print(score) change_list() # Global variable score used outside print(score)
After execution, it is found that the value of the global variable 5555 is used outside and the value of the local variable 6666 is used inside the function.
With the above basic knowledge points, you should pay attention to the concept of variable use range, and you will continue to learn when you are object-oriented.
Pass any number of parameters
Combination of general parameters and arbitrary parameters
In the process of writing code in Python, it is easy to happen that you do not know how many parameters there are. At this time, it is difficult to set the parameters during function definition. Fortunately, python has thought of this situation.
def show(*keys): print("The passed in parameters can be printed circularly") for key in keys: print(key) show(1,2,3,4,5,6,7)
When defining a function, the parameter position uses the * parameter name, and then cyclic printing can be performed at the code block position of the function weight, and any number of parameters can be captured.
What if there are general parameters and an indefinite number of parameters? Easy to do, use the following format.
def show(name,age,*keys): print("The passed in parameters can be printed circularly") print(name) print(age) for key in keys: print(key) show("www",18,1,2,3)
I hope you can find the rule now. When calling a function, first match the parameters defined by the function one by one. After all, it is found that there are no general parameters. Just pack the rest to * keys.
Do not write two parameters with *, such as def show(name,*keys,*keys1), which will report an error.
General parameters and any number of keyword parameters
There is also a case in the parameters that you need to transfer an indefinite number of keyword parameters. How to design this?
def show(**args): print("The passed in parameters can be printed circularly") for key in args.items(): print(key) show(name="Charlie", age=18)
In this case, you can treat all the parameters passed in as a dictionary and automatically aggregate them into a dictionary type of data.
If it matches the general parameters, the rule is also very simple.
def show(name,**args): print("The passed in parameters can be printed circularly") print(name) for key in args.items(): print(key) show(name="Charlie", age=18)
The above code first matches the keyword parameters. If the matching is successful, it is assigned to the corresponding keyword. For example, if the name variable above is assigned an eraser during function call, it is equal to the eraser. For example, age has no keyword parameter corresponding, so it has to be packaged to * * args.
Extension after function
This article only introduces about 50% of the contents of functions. There are still many interesting knowledge points about functions in Python, but you can't eat them at once. That will result in poor digestion, and it doesn't accord with the original design intention of snowball learning python. You can't master them completely until you roll them several times.
The knowledge points of deferred learning are as follows:
- Recursive function
- Anonymous function
- Higher order function
There is another knowledge point that you can expand now. I have learned the forms of various parameters. Have you ever thought about combining these together, such as how def show(name,age,*arg,**args) is parsed in the program? Is it possible to change the order?
def show(name, age, sex="male", *arg, **args): print("The passed in parameters can be printed circularly") print(name) for key in args.items(): print(key) show("Charlie", 18, "male", like=99)
Summary of this blog
Function, beginner stage, what is this, why, don't understand alas; In the middle of learning, it's very comfortable to write functions. There are functions easy to use in object-oriented; In the later stage of study, hurry up to realize this function. Whatever method is OK. Hurry up and get off work immediately.
Yes, the function is in a very difficult and simple link.
The last bowl of poisonous chicken soup
Programming needs a moment of insight, which many people have never had. O(∩ ∩) O ha ha~