This is the 15th day of my participation in the August Text Challenge.More challenges in August
📖 preface
Live and learn
At any time, we need to take the initiative to learn, have technical vision and drive, so that we can not only blow the bull of building rockets, but also land practical products and skills to help the company realize value, and also allow ourselves to have a certain income. Is the goal you should always pursue, and the value of breaking through the bottleneck.
Today the blogger talks with you about how to usePython
Function basics! Do not like spray, if there are suggestions welcome to supplement, discussion!
You can watch this blogger’s article about installation and LocalizationVsCode download, Installation and LocalizationAs well asPython series: windows10 configuration Python3.0 development environment!After installation, restart VsCode!
- What is a function
- Properties of a function
- Definition of a function
- Function call
- Parameters of a function
- On the use of global and local variables
🚀 last Come on! What is a function:
Functions are the most basic form of code abstraction, named blocks of code organized to implement a specific function. So why use functions?
-
Avoid code repeatability, that is, functions that can be used repeatedly.
-
Keep code consistent and easy to modify. That is, when a function is defined, it can be called in many places to achieve the same or similar function, and when these functions change, we only need to modify the function, do not bother to modify every place to achieve the function of the code.
-
Extensibility.
To put it simply: Function are the tools of a has a specific function, such as a hammer or a wrench, whenever we need to use these tools, we don’t need a temporary, please the teacher to make such a tool, this will be very cumbersome and consume large amounts of time, so we only need spend a cost to use these tools to the costs we can call its parameters, And the one who made these tools to fear other people don’t know the use of these tools, often give these tools with instructions (function), and to make these tools will use many material structure namely (function), a tool, of course, there will be named (function), namely when we will get some effect after use tools to complete, We can also call these effects (return values). Of course there are tools and of course there are toolboxes (classes).
🐱 🏍 last Come on! Function features:
Define a function to use
def
Statement, written in turnFunction name, parentheses, arguments in parentheses, and colons:
Then, in the indent block, write the function description, the function body, the return value of the functionreturn
Statement return.
Def function name (arguments 1, 2, 3,......) """ function description """ Function body return Return valueCopy the code
For example,
Def calc(x): """ :param x: enter a number :return: Print (res) print(res) print(calc) print(res)Copy the code
Note: statements inside the function body are executed as soon as the
return
, the function is finished, that is, inside the functionreturn
The following code is invalid and returns the result. If there is noreturn
Statement function, which is often referred to as a procedure, but actually returns by defaultNone
.
The definition of a function is usually similar to the definition of a variable. Defining a function gives the function a name, specifies the parameters contained in the function, and specifies the structure of the code block. Similar to variables, a function defines a block of code that is stored in memory in a way that is only executed when it is called. When we print the function name, we print the memory address. When the function name is printed in parentheses, it is the return value. Ex. :
def greater(name):
print("hello world,%s !"%name)
return name
greater("amanda") #调用函数,执行函数
print(greater) #打印函数地址
print(greater("Sunny Chen")) #调用函数,并且获取返回值
#输出为:
#hello world,Sunny Chen !
#<function greater at 0x00000241C37A3E18>
#hello world,Sunny Chen !
#amanda
Copy the code
When a function is called, an argument of the specified type is passed before the code block in the function body is executed. (Similar to Java, this is easy to learn with a foundation.)
👏 last Come on! Function definition:
3.1 Parameters and arguments
A parameter is a formal parameter, a piece of information that a function needs to do its job. Parameters take up no memory space and are only used when they are called and then released.
Arguments are the actual arguments, the information passed to a function when it is called. Such as:
Def greater(name): print("hello world,%s!" %name) return name greater("Sunny Chen") #Sunny ChenCopy the code
Above: call the function and pass in the argument namely
greater("Sunny Chen")
And the argument"Sunny Chen"
Pass to functiongreater()
, the value is stored in the parametername
In the.
3.2 Location parameters and Keyword Parameters
- Positional arguments –> When calling a function,
Python
Each argument must be associated with one of the parameters defined by the function. The simplest way to do this is based on the order of the arguments, known as positional arguments.
Def introduction(name,age,hobby): intro ="My name is %s,I'm %d years old,my hobby is %s."%(name,age,hobby) print(intro) introduction("Sunny Chen",21,"eating")Copy the code
- The keyword argument –> is passed to the function as a key-value pair. Because names and values are associated in arguments, order is not considered when passed in.
Def introduction(name,age,hobby) def introduction(name,age,hobby) intro ="My name is %s,I'm %d years old,my hobby is %s."%(name,age,hobby) print(intro) introduction(age=21,name="Sunny Chen",hobby="dancing")Copy the code
But when positional and keyword arguments are mixed:
- Positional arguments must be written to the left of keyword arguments
- The value of a parameter cannot be passed twice or more, but only once
Def introduction(name,age,hobby): intro ="My name is %s,I'm %d years old,my hobby is %s."%(name,age,hobby) print(intro) introduction("Sunny Chen",age="21", Hobby ="eating") # The position argument must be written to the left of the keyword argument # Introduction (name="Sunny Chen",21,hobby="eating") # The same argument can only be passed once #introduction("Sunny Chen",21,age="eating")Copy the code
Note: In the absence of a parameter group, the value passed must match the number of parameters.
3.3 Default Parameters
We can pass default values to arguments when defining functions, and use default values when the function is called without passing the value. Parameters with default values are called default parameters, and parameters without default values are required parameters. Mandatory parameters and optional default parameters are required when calling a function. Such as:
"@name: Sunny Chen @test: test font @msg: This is created by Sunny Chen @param: @return: Def introduction(name,age,hobby="runing"): Intro =" Name is %s,I'm %d years old, My hobby is %s."%(name,age,hobby) print(intro) Introduction ("Sunny Chen",age=21, Hobby ="eating") #Copy the code
3.4 parameter set
*args
–> Superfluous positional arguments passed byargs
To receive. That is, when you want to pass in more arguments than parameters, as positional arguments, the more arguments are received as tuples.
@param: @return: "def calc(x,y,*args):" def calc(x,y,*args): Res =x+y print(x,y) print(x,y,args)#*args Return res calc(1,2,7,8,6) calc(2,3,{"name":"sunny"}) # The dictionary as a whole is also received as a tuple calc(3,4,["sunny","Chen"],"hello world") calc(3,4,*["sunny","Chen"]) # Calc (3,4,*"sunny") #1 2 (7, 8, 6) #2 3 ({'name': 'sunny'},) #3 4 (['sunny', 'Chen'], 'hello world') #3 4 ('sunny', 'Chen') #3 4 ('s', 'u', 'n', 'n', 'y')Copy the code
**kwargs
–> Superfluous keyword arguments passed bykwargs
To receive. That is, you want to pass in more arguments than parameters as keyword arguments, which are received as dictionaries
@param: @return: "def calc(x,y,**kwargs):" def calc(x,y,**kwargs): Res =x+y #print(x,y) print(x,y,kwargs)#**kwargs In the form of a dictionary to receive return res calc (x = 1, y = 3, name = "sunny") calc (1, 2, * * {" name ":" Chen "}) # output is: # 1 3 {' name ':' sunny '} # 1 2 {' name ': 'Chen'}Copy the code
You can pass in any parameter when you define *args and **kwargs at function values. Superfluous positional arguments, passed into the function, are stored as tuples in *args; The extra keyword arguments, passed in to the function, are stored in **kwargs as dictionaries
@param: @return: "def calc(x,y,*args,**kwargs): def calc(x,y,* *args,**kwargs): Res = x + y print (x, y, args, kwargs) # * args. Return res calc(1,23,"222",["Sunny Chen"," mr-chen "],greater="hello world") # #1 23 ('222', ['Sunny Chen', 'Mr-Chen']) {'greater': 'hello world'}Copy the code
On! Function call:
Here we need to briefly understand the following variables about the scope of what?
-
L: local, local scope, that is, the variable defined in the function.
-
If you want additional recommendations on the local scope of a parent function. If you want additional recommendations on this, if you want additional recommendations on the local scope of a parent function.
-
G: global, a global variable, is a module level defined variable.
-
B: Built-in, system built-in module variables, such as int,bytearray, etc.
The search variables are in order of priority: local scope > outer scope > global scope in the current module > Python built-in scope, also known as LEGB
Perhaps we can better understand the relationship between the four scopes by using the following code:
"@name: Sunny Chen @test: test font @msg: This is created by Sunny Chen @param: @return: X =int(1) ---->B y =2 # def infunc(): Print (inpara) infunc() outfunc()Copy the code
At the same time, we need to know that the scope of a variable in a function is only related to the declaration of the function, not the location of the function. Here’s an example:
@param: @return: "" # function name --> function memory address; Def foo(): name ="zhangsan" def bar(): name =" wangwu" def mitt(): name ="zhangsan" def foo(): name ="lisi" def bar(): name =" wangwu" def mitt(): Print (name) return mitt return bar foo()() # equivalent to --------------- # bar =foo() # #mitt =bar() #mitt =bar() #mitt =bar() #mitt =bar() #mitt =bar() #mitt =bar() #mitt =bar(Copy the code
This result is
wangwu
Rather thanzhangsan
, indicating that the scope of a variable in a function is only related to the declaration of the function, and has nothing to do with the location of the function call. Otherwise, the output must be ->zhangsan
, because if simple callmitt()
The variable isName = "zhangsan"
Is printed aszhangsan
.
On! On the use of global and local variables:
Outside a function, a variable initially assigned by a piece of code that can be called by multiple functions and whose scope is global is called a global variable.
A variable name defined in a function can only be referenced inside the function, but not outside the function. If its scope is local, it is called a local variable. Such as:
@param: @return: "name ="Sunny Chen" # def foo(): name ="xiaojia" print(name) def bar(): Name ="mengxia" print(name) bar() print(name) foo(Copy the code
global
–> If you want to modify a global variable inside a function, use this commandglobal
The key
"@name: Sunny Chen @test: test font @msg: This is created by Sunny Chen @param: @return: Def foo(): name ="xiaojia" print(name) def bar(): Name ="mengxia" print(name) bar() print(name) Print (name) print(name) print(nameCopy the code
nonlocal
–> If you want to modify the variables of the parent function within the child function, use this parameternonlocal
Key words
@param: @return: "name ="Sunny Chen" # def foo(): name ="xiaojia" print(name) def bar(): Print (name) bar() print(name) # Print (name) # print(name) # print(nameCopy the code
Note: Bothglobal
ornonlocal
, must precede variable modifications. Otherwise, an error will be reported.
Here we go :Python Function basics! Share the end, go and try it!
🎉 finally
-
For more references, see here:Chen Yongjia’s blog
-
Like the small partner of the blogger can add a concern, a thumbs-up oh, continue to update hey hey!