Python -- function, python

Source: Internet
Author: User

Python -- function, python

A function is a variable. Defining a function is equivalent to assigning a function body to the function name.

1. Call Parameters

Def test0 (x, y, z): # defines the function test0, the form parameter x, y, z
Print ("x = % d, y = % d, z = % d" % (x, y, z) # output the values of the parameters in sequence
Test0 (1, 2, 3) # location parameter call
Test0 (x = 2, z = 0, y = 1) # keyword call
Test0 (2, z = 1, y = 3) # Call the location parameter and keyword. The location parameter must be in front

-----------------------------------------------------------------------------
X = 1, y = 2, z = 3
X = 2, y = 1, z = 0
X = 2, y = 3, z = 1
========================================================== ============================================
Def test1 (x, y = 2): # defines the default parameter, which can be omitted.
Print ("x = % d, y = % d" % (x, y ))

Test1 (1)
-----------------------------------------------------------------------------
X = 1, y = 2
========================================================== ============================================

Def test2 (* args): # variable parameters, which can be transferred multiple times. The keyword parameters can be converted to the meta-group tuple.
Print (args)
Test2 (1, 2, 3)
Test2 (* [1, 2, 3])
-----------------------------------------------------------------------------
(1, 2, 3)
(1, 2, 3)
========================================================== ============================================
Def test3 (** kwargs): # The dictionary is used as the form parameter and multiple parameters can be passed. The passed value is key: value.
Print (kwargs)
Print (kwargs ['name'])
Print (kwargs ['age'])
Print (kwargs ['sex'])
Test3 (name = 'xy', age = 23, sex = "N ")
Test3 (** {'name': 'xy', 'age': 23, 'sex': 'n '})
-----------------------------------------------------------------------------
{'Name': 'xy', 'age': 23, 'sex': 'n '}
Xy
23
N
{'Name': 'xy', 'age': 23, 'sex': 'n '}
Xy
23
N
========================================================== ============================================

Def test4 (name, ** kwargs): # location parameter and dictionary parameter transfer value
Print (name, kwargs)
Test4 ('xy', age = 23, sex = 'n ')
-----------------------------------------------------------------------------
Xy {'age': 23, 'sex': 'n '}
========================================================== ============================================
Def test5 (name, age = 18, ** kwargs): # transfer location parameters, keyword parameters, Dictionary Parameters
Print (name, age, kwargs)
Test5 ('xy', sex = 'n', holobby = 'belle', age = 23) # If the parameter does not match, move it to ** kwargs
-----------------------------------------------------------------------------
Xy 23 {'sex': 'n', 'hobby': 'belle '}
========================================================== ============================================
Def test6 (name, age, * args, ** kwargs): # define multiple type parameters, tuple, and Dictionary
Print (name, age, args, kwargs)
Test6 ('xy', 23, 'python', 'perl ', linux = 'shell', SQL = 'mariadb', sex = 'n ')

# Match the parameters in sequence, and the transmitted positional parameters must be prior to the keyword parameters.
-----------------------------------------------------------------------------
Xy 23 ('python', 'perl ') {'linux': 'shell', 'SQL': 'mariadb', 'sex': 'n '}
========================================================== ============================================

Ii. return Value of the Function

Return in the function indicates that the function has ended.

The return value of a function in Python can be a parameter, or multiple parameters can be returned in the format of tuples.

Def return_test ():
Print ("line one ")
Print ("line two ")
Return 'hello', ['Nice ', 'to', 'meet', 'you'], 666 # multiple parameters are returned.
Print ("line three") # Do not run after return
Print (return_test () # print the function return value
-----------------------------------------------------------------------------

Line one
Line two
('Hello', ['Nice ', 'to', 'meet', 'you'], 666) # The returned value is in tuple format.

========================================================== ============================================

Iii. Anonymous Functions

An anonymous function can have only one expression.returnThe returned value is the result of this expression.

The function has no name, so you don't have to worry about Function Name Conflict.

Calc = lambda x: x ** 3 #lambdaIndicates an anonymous function.xFunction Parameters

Print ("calc is % s" % calc (3 ))

-----------------------------------------------------------------------------

Calc is 27

========================================================== ============================================

Iv. local and global variables in the function

Name = 'xy' # name is a global variable.
Def test7 (name): # the name in the function is a local variable.
Print ("before change", name)
Name = "effecect" # change the variable value in the function.
Print ("after change", name) # print the value of the local variable name in the function
Test7 (name)
Print (name)
-----------------------------------------------------------------------------
Before change xy
After change effecect
Xy # values outside the Function
========================================================== ============================================
School = "ahxh edu"
Def test8 (name): # The global variable is not partially changed.
Global school # global, which declares global variables in the function and is not recommended to be modified.
School = 'xwxh edu' # assign a value to the global variable
Print (school)
Test8 (school)
Print (school)
-----------------------------------------------------------------------------
Xwxh edu # value in the function
Xwxh edu # The global variable has been changed in the function.
========================================================== ============================================
Names_list = ['xy', 'jack', 'Lucy ']
Def test9 (): # When list, tuple, and dictionary are passed, the address is passed. The global variable can be changed in the function.
Names_list [0] = 'effect'
Print ("inside func", names_list)
Test9 ()
Print (names_list)
-----------------------------------------------------------------------------
Inside func ['effect', 'jack', 'Lucy '] # values in the function
['Effect', 'jack', 'Lucy '] # values outside the Function
========================================================== ============================================
5. recursion of functions
Recursively start the program for about 999 times to protect the process from being shut down. recursion must have clear end conditions.
To reduce the number of deep-level recursive algorithms, the efficiency of recursion is not high, which may easily cause stack overflow.
Def calc (n ):
Print (n)
Return calc (n + 1) # infinite Recursion
Calc (0)
-----------------------------------------------------------------------------
996
Traceback (most recent call last ):
File "recursive. py", line 8, in <module>
Calc (0)
File "recursion. py", line 7, in calc
Return calc (n + 1)
File "recursion. py", line 7, in calc
Return calc (n + 1)
File "recursion. py", line 7, in calc
Return calc (n + 1)
[Previous line repeated 992 more times]
File "recursion. py", line 6, in calc
Print (n)
RecursionError: maximum recursion depth exceeded while calling a Python object
========================================================== ============================================
Def calc (n ):
Print (n)
If int (n/2) = 0:
Return n
Return calc (int (n/2) # recursively call a function
Calc (10)
-----------------------------------------------------------------------------
10
5
2
1
========================================================== ============================================
Vi. High-Order Functions

Pass a function name as a real parameter to another function

The returned value contains the function name.


Def add (x, y, f): # High-order functions, which can pass Functions
Return f (x) + f (y)

Res = add (3,-6, abs) # abs is a python built-in function that calculates the absolute value.
Print ("res = % d" % (res ))
-----------------------------------------------------------------------------
Res = 9

========================================================== ============================================

The function name points to the function body and passes the function name to the form parameter. The form parameter has a common function body address.

Import time # import time module

Def high1 ():
Time. sleep (3) # sleep for 3 seconds
Print ("this is high1 ")
Def high2 (func ):
Start_time = time. time ()
Func () # Call the form Parameter Function func (). The real parameter is high1 ()
Stop_time = time. time ()
Print ("the func run time % s" % (stop_time-start_time) # End minus start time, program running time
High2 (high1)

-----------------------------------------------------------------------------

This is high1
The func runtime 3.015038013458252


========================================================== ============================================
Python built-in functions

Built-in Functions
Abs () dict () help () min () setattr ()
All () dir () hex () next () slice ()
Any () divmod () id () object () sorted ()
Ascii () enumerate () input () oct () staticmethod ()
Bin () eval () int () open () str ()
Bool () exec () isinstance () ord () sum ()
Bytearray () filter () issubclass () pow () super ()
Bytes () float () iter () print () tuple ()
Callable () format () len () property () type ()
Chr () frozenset () list () range () vars ()
Getattr () locals () repr () zip () classmethod ()
Compile () globals () map () reversed () _ import __()
Complex () hasattr () max () round ()
Delattr () hash () memoryview () set ()

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.