Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of definition and use of Python function

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the definition and use of Python function example analysis, the article introduces in great detail, has a certain reference value, interested friends must read it!

Definition of function

What is a function? A-> function is a block of code with a specific function that can be reused (in the previous section on data types, there are actually a lot of Python built-in functions). It makes our program more modular without having to write a lot of repetitive code.

The function can be saved in advance and given a unique name, and you can use this code as long as you know its name. The function can also receive data, make different operations according to the different data, and finally feedback the processing results to us.

From this we know:

The step of encapsulating the steps of a thing together and getting the final result is the process of the function.

The function name represents what the function is going to do.

The function body is the process of realizing the function of the function.

In practical work, we also call the implementation of a function "implementing a method or implementing a function"

The function can help us reuse the function, and we can know the function of the function by the function name.

Classification of functions

Built-in functions: in the previous section on data types, there have been a lot of Python built-in functions. Such as input, id, type, max, min, int, str, etc., these are all built-in functions of Python. That is, the function that Python has defined for us, we can just use it.

Custom function: because each business is different, the requirements are also different. Python can't provide us with all the functionality we want, so we need to develop and implement what we want. This part of the function, we call it a custom function.

Whether they are built-in functions or custom functions, they are written in the same way.

The creation method of function-def

The function of def keyword: realize the creation of Python function.

The def keyword defines a function: defining a function, that is, creating a function, can be understood as creating a tool that has some purpose. The definition function needs to be implemented with the def keyword. The specific syntax format is as follows:

Def function name (argument list): todo something # multiple lines of code that implements a specific function [return [return value]] # is the optional part enclosed in [], which can be used or omitted. The function name is actually an identifier that conforms to the Python syntax, but it is not recommended to use simple identifiers such as a, b, c as the function name, it is best to reflect the function of the function (such as user_info, user_mobile). Parameter list: sets how many parameters the function can accept, separated by commas (,). # > [return [return value]]: as an optional parameter of the function, it is used to set the return value of the function. In other words, a function can return a value or no return value, depending on the actual situation.

Note that when you create a function, you must keep a pair of empty "()" even if the function does not require arguments, otherwise the Python interpreter will prompt for a "invaild syntax" error. In addition, if you want to define an empty function with no function, you can use the pass statement as a placeholder.

Examples are as follows:

Def user_name (): print ('this is a\' user_name\ 'function') user_name () # > the execution result is as follows # > this is the return value of a 'user_name' function-return

Return means return, which is the keyword that returns the result of the function, so the return value of the function is also implemented through return.

It is important to note that return can only be used inside a function; return supports returning all data types, and when a function returns, we can assign a new variable to the return value to use.

From this, we conclude that:

Return is the keyword that returns the result of the function

Return can only be used in the function body.

Return supports returning all data types

A function with a return value can be assigned directly to a variable

Examples of the usage of return are as follows:

Def add (return b): C = a + b return c # function assigns a value to the variable result = add (axi1memb 1) print (result) # function returns the value as the actual parameter print of other functions (add (3prime4))

It is important to note that return statements can appear multiple times in the same function, but as long as one of them is executed, it will directly end the execution of the function.

Now let's try to customize a capitalize function using the return keyword. Examples are as follows:

Def capitalize (data): index = 0 temp =''for item in data: if index = 0: temp = item.upper () else: temp + = item index + = 1 return tempresult = capitalize (' hello, Jack') print (result) # > > the execution result is as follows # > Hello, Jack

Once again, notice that as long as one is executed, the execution of the function is directly terminated.

The difference between return and print

Print simply prints objects and does not support assignment statements.

Return is the return of the result of the execution of the function and supports assignment statements; however, we can print functions with renturn values in print.

Passing parameters of a function

Required parameters: usually the most commonly used, must pass a certain number of parameters

Default parameter: can be passed or not when the function is called, and the default value will be used if it is not passed

Uncertain parameters: variable length parameters (also known as variable parameters)

Keyword parameters: variable length, but need to pass parameters in the form of key-value

Required parameters

What are required parameters? -> when defining a function, there is no default value and the parameters that must be passed when the function is executed; and the order is the same as the parameter order, which is the required parameter.

The parameters defined in the function have no default values, and an error will be reported if the parameters are not passed in when the function is called.

When defining a function, there is no equal sign and default value after the parameter.

Wrong function parameter passing method: def add (axi1, bail1)

Examples of errors are as follows:

Def add (a, b): return a + bresult = add () print (result) # > > the execution result is as follows # > TypeError: add () missing 2 required positional arguments:'a 'and'

The correct examples are as follows:

Def add (a, b): return a + bresult = add (1,2) print (result) # > the execution result is as follows: the add function has two parameters, the first parameter is a, the second parameter is b # > > the two integers passed in are assigned to the function parameters an and b in positional order, and the parameters an and b are called positional parameters

The number of parameters passed must be equal to the number of parameter lists

The parameters are passed according to the position of the parameters defined by the function, and the passed parameters are required to correspond to the parameters defined by the function one by one.

If the number of parameters passed is not equal to the number of parameters defined by the function, the runtime will report an error

Example of the number of parameters passed in error is as follows:

Def add (a, b): return a + bsum = add (1,2,3) # > > the execution result is as follows # > sum = add (1,2,3) # > TypeError: add () takes 2 positional arguments but 3 were given default parameters

When defining a function, the defined parameter contains the default value, and the parameter is given a default value through the assignment statement.

Using default parameters can simplify the call of a function, especially if the function needs to be called frequently

If the default parameter is given a new value when the function is called, the function will work with the newly passed value first

Examples are as follows:

Def add (a, b, cym3): return a + b + cresult = a; 2 corresponding to add (1,2) # 1; no value passed into C, use the default value of C 3. Print (result) # > execution result is as follows # > 6def add (a, b, cym3): return a + b + cresult = a; 2 corresponding to add (1,2,7) # 1; the value passed into C is 7, and the default value of C is not used. Print (result) # > execution results are as follows # > 10 uncertain parameters (variable parameters)

This parameter does not have a fixed parameter name and number (I don't know exactly what the parameter name is).

The format of uncertain parameters is as follows:

Def add (* args, * * kwargs): pass# * args: merge values without parameters into tuples # * * kwargs: merge assignment statements with parameters and default values into dictionaries

* args represents: merge values without parameters into tuples

* * kwargs represents: merge assignment statements with parameters and default values into a dictionary

It seems difficult to understand in terms of definition and concept, so let's take a look at it through an example:

Def test_args (* args, * * kwargs): print (args, type (args)) print (kwargs, type (kwargs)) test_args (1, 2, 3, name='Neo', age=18) # > > the execution result is as follows # > (1,2,3) # > > {'name':' Neo' 'age': 18} # > > args converts the input parameters into a tuple # > kwargs converts the input assignment statement into a dictionary # > when in use We can also use these parameters according to the characteristics of tuples and dictionaries Examples are as follows: def test_args (* args, * * kwargs): if len (args) > = 1: print (args [2]) if 'name' in kwargs: print (kwargs [' name']) test_args (1, 2, 3, name='Neo', age=18) # > > the execution result is as follows # > 3 according to tuple characteristics Printout values with args index 2 # > Neo according to dictionary characteristics The key of the printout kwargs is value def test_args (* args, * * kwargs): if len (args) > = 1: print (args [2]) else: print ('the length of the current args is less than 1') if 'name' in kwargs: print (kwargs [' name']) else: print ('there is no key name element in the current kwargs') test_args (1, 2, 3, name1='Neo' Age=18) # > execution results are as follows # > 3 according to tuple characteristics Printout values with args index 2 > > there are no elements with key name in the current kwargs (the kwargs passed in is name1='Neo', age=18 No name) Parameter rules

Def add (a, bread1, * args, * * kwargs)

The definition of parameters from left to right is a-required parameter, b-default parameter, variable * args parameter, variable * * kwargs parameter.

The parameter passing of the function is very flexible

The parameters of required parameters and default parameters are also very diversified.

Examples are as follows:

Def add (a, bread2): print (a + b) # Let's take a look at how this function can pass parameters to execute add (1, 2) # the result is: 3add (1) # the result is: 3add (aqui1) 3add (add 1) # the result of execution is: TypeError: add () missing 1 required positional argument:'a'. # (because an is a required parameter It is not possible to pass in only the parameters of b) def test (a, b, * args): print (a, b, args) int_tuple = (1,2) test (1,2, * int_tuple) # > > the execution result is as follows 2) # * def test (a, b, * args): print (a, b, args) int_tuple = (1,2) test (a, b, * int_tuple) * int_tuple) # > execution result is as follows # > TypeError: test () got multiple values for argument'aemployees # > prompt us to repeat the parameters This is because when required parameters, default parameters, and variable parameters are together. If you need to assign a value to pass parameters, you need to put the variable parameters first, followed by the required parameters and default parameters. (this is a special case) # * def test (* args, a, b): print (a, b, args) int_tuple = (1,2) test (axi1, baux2, * int_tuple) # > > the execution result is as follows # > 12 (1) 2) # > > this way of changing required parameters, default parameters, and variable parameters Generally speaking, we do not recommend def test (a, baked 1, * * kwargs): print (a, b, kwargs) test (1, 2, name='Neo') test (name='Jack', age=18 1, baked 2, name='Jack') test (name='Jack', age=18, axi1, baked 2) # > > the execution result is as follows # > 1 2 {'name':' Neo'} # > > 12 {'name':' Jack'} # > 12 {'name':' Jack', 'age': 18}

Note: if the order of passing parameters changes, be sure to use assignment statements to pass parameters.

Small exercise of function

Requirements: define a login function, pass the parameter username,password into the function, and return "login successful" when username value is admin and password value is string 123456; otherwise return "Please log in again"

Def login (username, password): # define a login function, pass in username, password required parameter if username = = "admin" and password = = "123456": # use if statement Judge the username and password as "admin" and "123456" print ("login successful") # return the login success else: # use the else clause to handle the case where the username and password are not "admin" and "123456" print ("Please login again") # sign in again when returned # call the function Pass' admin','123456' 'and' test','123456' data test results login (username= "admin", password= "123456") # print function test results login (username= "test", password= "123456") # print the parameter type definition of the function test results

In the previous article, we learned the definition and use of the function. When defining the parameters, we do not know what the data type of the parameter is. It is judged by the function body according to the business call scenario. If the type passed in does not match the free nature, an error will be generated. Now we learn a way to define the parameter type along with the parameter when defining the function, so that we can know the data type that needs to be passed in for each parameter.

Let's look at an example:

Def person (name:str, age:int=18): print (name, age)

Required parameter: parameter name + colon + data type function, which is the data type that declares the required parameter.

Default parameter: parameter name + colon + data type function + equal sign + default value, which is the data type that declares the default parameter.

It should be noted that the function definition data type does not have this feature until after python 3.7,

Although we define the data type for the function parameter, the parameter type is still not verified when the function is executed, and it is still judged by the function body according to the business call scenario. This method of definition is only a simple naked eye view.

Examples are as follows:

Def add (a: int, b: int = 3): print (a + b) add (1,2) add ('Hello',' World') # > > execution result is as follows: # > HelloWorlddef add (a: int, b: int = 3, * args:int, * * kwargs:str): print (a, b, args, kwargs) add (1,2,3, '4legs, name='Neo') # > > execution result is as follows: # > 12 (3) '4') {' name': 'Neo'}

We found that the functions executed did not report errors, and add ('Hello',' World') were spliced together in a cumulative way.

Therefore, although we have defined the int type, we do not do any verification, but simply tell us that the parameter is the int type through the naked eye, and then we can write our own code to verify it when we enter the advanced stage of python.

Global variables and local variables

Global variables: variables that take effect in the current py file

The variables of the code block at the top of the python script

Global variables can be read and used within a function

Local variables: inside the function, inside the class, lamda. Whose scope is only in functions, classes, and lamda

Variables defined in the body of a function

Local variables cannot be used outside of their own functions

Global variable

Examples are as follows:

# coding:utf-8name = 'Neo'age = 18def test01 (): print (name) def test02 (): print (age) def test03 (): print (name, age) test01 () test02 () test03 () # > > the execution result is as follows: # > > Neo# > declare > > Neo variables > > here we can see that declared global variables can be used by local variables in multiple functions.

Examples are as follows:

# coding:utf-8name = 'Neo'age = 18def test01 (): name =' Jack' age = 17 print ('this is a local variable inside the function', name, age) test01 () print ('this is a global variable outside the function', name, age) # > the execution result is as follows: # > this is the local variable inside the function, Jack variables > this is the global variable outside the function, Neo variables > > here we declare the global variable At the same time, the value of the variable is changed in the function body to make it a local variable. At the same time, according to the result of the printout, we can see that the local variable only acts on the body of the function.

Is it true that global variables cannot be modified in the function body? Of course, it can be achieved with the help of the keyword global.

Global keyword

The function of the global keyword: global variables can be modified in the function body

The usage of the global keyword: examples are as follows

# coding:utf-8name = 'Neo'def test (): global name name =' Jack' print ('inside the function\' name\') print (the value of\ 'name\' outside the function is:', name) # > the execution result is as follows: # > the value of 'name' inside the function is: Jack# > the value of the name' outside the function is: Jack

Note: it is not recommended to use global to modify global variables in daily development work.

Let's look at another case:

Test_dict = {'name':' Neo', 'age':' 18'} def test (): test_dict ['sex'] =' man' test_dict.pop ('age') print (' inside the function\ 'test_dict\' is:', test_dict) test () print ('outside the function\' test_dict\'is:' Test_dict) # > the execution result is as follows: # > the value of 'test_dict' inside the function is {' name': 'Neo',' sex': 'man'} # > the value of' test_dict' outside the function is: {'name':' Neo', 'sex':' man'}

Previously, we modified the value of the variable in the function through the global keyword, why not use the global keyword here, modify the value of test_dict in the function body but affect the value of the variable outside the function?

In fact, global variables modified by the global keyword only support numbers, strings, empty types and Boolean types. If you want to use the dictionary and list type of global variables in local variables, you do not need to be guided by the global keyword.

Recursive function

What is a recursive function? -> in popular terms, a function executes itself over and over again, which is a recursive function. (it is usually because the function is not satisfied with the result of its execution that it needs to be executed repeatedly.)

The definition of Recursive function

Examples are as follows:

Def test (a): print (a) return test (a) # directly executes its own function test (1) # > the result is as follows: # > > outline > 1.... It will be carried out all the time, and it may cause a crash. Don't try. Count = 0def test (): global count count + = 1 if count! = 5: print ('\ 'count\') is not satisfied and needs to be re-executed. The current value of\ 'count\' is% s'% count) return test () else: print (the value of 'current\' count\'is% s'% count) test () > the execution result is as follows: # > 'count' condition is not met and needs to be re-executed. The current condition that the value of 'count' is count' >' is not met and needs to be re-executed. The current condition that the value of 'count' is count' >' is not met and needs to be re-executed. The current condition that the value of 'count' is count' >' is not met and needs to be re-executed. The value of the current 'count' > > the value of the current' count' is 5 recursive function description

First of all, we need to know the impact of recursive functions. Recursive functions keep calling their own functions for an infinite loop, which will cause memory overflow, and our computer may crash.

Although recursive functions make it convenient for us to describe a complex algorithm (processing process) with a short piece of code, we must use it with caution. Using loops to deal with it is a safe solution.)

So we should try to avoid using recursive functions, if we really want to use recursion, be sure to give the exit recursion scheme.

Lambda-Anonymous function

The function of the lambda function: define a lightweight function; lightweight is delete on the fly, which is very suitable for completing a function, but this function is only used in this place. That is to say, if the function is not reused and the business is simple, we can define the function through lambda.

Examples of usage of the lambda function are as follows

# two ways to define anonymous functions # method 1: anonymous functions with no parameters test = lambda: value # lambda + colons + value values are assigned to a variable test () # variable name + parentheses, and the lambda anonymous function is defined. (value actually has return effect) # method 2: anonymous function with parameters test = lambda value,value:value*value # lambda + two parameters + colons + two value simple handling Assign a value to a variable test (3,5) # anonymous function test = lambda:1result = test () print (result) # > execute as follows: # > > anonymous * # anonymous function with parameters test = lambda a, b: a+bresult = test (1 3) print (result) # > execution result is as follows: # > > test = lambda a, b: a > bresult = test (1,3) print (result) # > execution result is as follows: # > False

Let's take a look at another example to deepen the understanding of lambda anonymous functions.

Users = [{'name':' Neo'}, {'name':' Jack'}, {'name':' Lily'}] users.sort (key=lambda user_sort: user_sort ['name']) print (users) # > the execution result is as follows: # > [{' name': 'Jack'}, {' name': 'Lily'} {'name':' Neo'}] # > We see that {'name':' Jack'} is at the front. Pass in each member of the list as a parameter through lambda, # >, and sort the value in the element that specifies key as name as the sort object.

So much for the simple use of lambda. The high-level usage of lambda anonymous functions will be explained in detail in the following advanced syntax chapters.

Function exercise

Using function to realize student information database

Now that we have learned the basics of functions, let's make a summary and contact. Practice a case of a student information base, and as we learn in later chapters, we will improperly upgrade and optimize the information base to achieve functions that can really be used.

Next, we first define the basic structure of the student information base, and then develop the add, delete, change and query functions of the information base.

# coding:utf-8 "" @ Author:Neo @ Date:2020/1/14 @ Filename:students_info.py @ Software:Pycharm "students = {# define a student dictionary with key as id Value is student information (name, age, class_number, sex) 1: {'name':' Neo', 'age': 18,' class_number': 'Aids,' sex': 'boy'}, 2: {' name': 'Jack',' age': 16, 'class_number':' B' 'sex':' boy'}, 3: {'name':' Lily', 'age': 18,' class_number': 'Aids,' sex': 'girl'}, 4: {' name': 'Adem',' age': 18, 'class_number':' C' 'sex':' boy'}, 5: {'name':' HanMeiMei', 'age': 18,' class_number': 'age':,' sex': 'girl'}} def check_user_info (* * kwargs): # define a check_user_info function Check student information incoming missing if 'name' not in kwargs: return' did not find student name'if 'age' not in kwargs: return' missing student age'if 'sex' not in kwargs: return' missing student gender'if 'class_number' not in kwargs: return' missing student class' return Truedef get_all_students (): # define a get_all_students function Get all student information and return for id_, value in students.items (): print ('student number: {}, name: {}, age: {}, gender: {}, class: {}' .format (id_, value ['name'], value [' age'], value ['sex']) Value ['class_number']) return studentsdef add_student (* * kwargs): # define an add_student function Perform the operation of adding student information and verify it Student id increment check = check_user_info (* * kwargs) if check! = True: print (check) return id_ = max (students) + 1 students [id_] = {'name': kwargs [' name'], 'age': kwargs [' age'], 'sex': kwargs [' sex'] 'class_number': kwargs [' class_number']} def delete_student (student_id): # define a delete_student function Perform the operation of deleting student information And judge whether there is if student_id not in students: print ('{} does not exist '.format (student_id)) else: user_info = students.pop (student_id) print (' student ID is {}, {} classmate's information has been deleted '.format (student_id, user_info [' name'])) def update_student (student_id) * * kwargs): # define a update_student function Perform the operation of updating student information And verify if student_id not in students: print ('this student ID: {}' .format (student_id)) check = check_user_info (* * kwargs) if check! = True: print (check) return students [student _ id] = kwargs print ('classmate information updated') # update_student (1, name='Atom', age=16, class_number='A') Sex='boy') # execute the update student information function And view the result # get_all_students () def get_user_by_id (student_id): # define a get_user_by_id function, you can query student information through student id return students.get (student_id) # print (get_user_by_id (3)) def search_users (* * kwargs): # define a search_users function You can make a fuzzy query through the key information of students values = list (students.values ()) key = None value = None result = [] if 'name' in kwargs: key =' name' value = kwargs [key] elif 'sex' in kwargs: key =' sex' value = kwargs ['sex'] elif' class_number' in kwargs: key = 'class _ number' value = kwargs [key] elif 'age' in kwargs: key =' age' value = kwargs [key] else: print ('search keyword not found') return for user in values: if user [key] = value: result.append (user) return resultusers = search_users (sex='girl') print (users) # > Enforcement The row result is as follows: # > [{'name':' Lily'' 'age': 18,' class_number': 'functions,' sex': 'girl'}, {' name': 'HanMeiMei',' age': 18, 'class_number':' functions, 'sex':' girl'}] these are all the contents of the article "sample Analysis of the definition and use of Python functions" Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report