Python functions and python Functions

Source: Internet
Author: User

Python functions and python Functions

Pythond functions are written by a new statement, that is, def, def is an executable statement-the function does not exist until Python runs def.

A function is passed through a value assignment, and a parameter is passed to the function through a value assignment.

The def statement creates a function object and assigns it to a variable name. The general format of the def statement is as follows:

Copy codeThe Code is as follows:
Def function_name (arg1, arg2 [,...]):
Statement
[Return value]

The return value is not required. If no return statement is available, Python returns None by default.

Naming rules for function names:

The function name must start with an underscore (_) or a letter. It can contain any combination of letters, numbers, or underscores. You cannot use any punctuation marks;

Function names are case sensitive.

The function name cannot be a reserved word.

Python uses the namespace concept to store objects. This namespace is the region where the objects are applied. Different objects exist in different scopes. The following are the scope rules for different objects:

Each module has its own global scope.

The objects defined by the function belong to a local scope. They are valid only within the function and do not affect objects in the global scope.

The value assignment object belongs to a local scope, unless it is declared using the global keyword.

The LGB rule is the rule for finding names in Python. The following is the LGB rule:

1. Most name references are found in three scopes: Local, Global, and Build-in ).

Copy codeThe Code is as follows:
>>> A = 2
>>> B = 2
>>> Def test (B ):
... Test = a * B
... Return test
>>> Print test (10)
20

B is found in the local scope, and a is found in the global scope.

2. If you want to change the global scope object in a local scope, you must use the global keyword.

Copy codeThe Code is as follows:
# When global is not used
>>> Name = "Jims"
>>> Def set ():
... Name = "ringkee"
...
>>> Set ()
>>> Print name
Jims

# Global usage
>>> Name = "Jims"
>>> Def set1 ():
... Global name
... Name = "ringkee"
...
>>> Set1 ()
>>> Print name
Ringkee

3. the 'global' statement maps the value assignment name to the scope of a module containing it.

A function parameter serves as a bridge between the function and the outside, and can receive values passed by the outside. The rules for passing parameters are as follows:

4. parameter name assignment in a function does not affect the caller.

Copy codeThe Code is as follows:
>>> A = 1
>>> Def test ():
... A = a + 1
... Print
...
>>> Test ()
2
>>>
1 # a value unchanged

5. Changing a variable object parameter in a function will affect the caller.

Copy codeThe Code is as follows:
>>> A = 1
>>> B = [1, 2]
>>> Def test (a, B ):
... A = 5
... B [0] = 4
... Print a, B
...
>>> Test (a, B)
5 [4, 2]
>>>
1
>>> B
[4, 2] # value B has been changed

The parameter is an object pointer and does not need to define the passed object type. For example:

Copy codeThe Code is as follows:
>>> Def test (a, B ):
... Return a + B
...
>>> Test (1, 2) # numeric type
3
>>> Test ("a", "B") # signature type
'AB'
>>> Test ([12], [11]) # list
[12, 11]

The parameters in the function receive the passed values. The parameters can be divided into default parameters, such:

Def function (ARG = VALUE)
Tuples parameters:

Def function (* ARG)
Dictionary parameters:

Def function (** ARG)
Some function rules:

The default value must be after a non-default parameter;

In a single function definition, only one tuple parameter (* ARG) and one dictionary parameter (** ARG) can be used ).

The tuple parameter must be followed by the connection parameter and default parameter.

Dictionary parameters must be defined at the end.

1. Common functions
1. abs (x)

Abs () returns the absolute value of a number. If a plural number is given, the return value is the modulo of the plural number.

Copy codeThe Code is as follows:
>>> Print abs (-100)
100
>>> Print abs (1 + 2j)
2.2360679775

2. callable (object)

The callable () function is used to test whether the object is callable. If yes, 1 (true) is returned; otherwise, 0 (false) is returned ). Callable objects include functions, methods, code objects, classes, and class instances that have defined the "call" method.

Copy codeThe Code is as follows:
>>> A = "123"
>>> Print callable ()
0
>>> Print callable (chr)
1

3. cmp (x, y)

The cmp () function compares two objects, x and y, and returns an integer based on the comparison result. If x <y,-1 is returned. If x> y, 1 is returned, if x = y, 0 is returned.

Copy codeThe Code is as follows:
>>> A = 1
>>> B = 2
>>> C = 2
>>> Print cmp (a, B)
-1
>>> Print cmp (B,)
1
>>> Print cmp (B, c)
0

4. divmod (x, y)

The divmod (x, y) function completes Division operations and returns the quotient and remainder.

Copy codeThe Code is as follows:
>>> Divmod (10, 3)
(3, 1)
>>> Divmod (9, 3)
(3, 0)

5. isinstance (object, class-or-type-or-tuple)-> bool

Test Object Type

Copy codeThe Code is as follows:
>>> A = 'isinstance Test'
>>> B = 1234
>>> Isinstance (a, str)
True
>>> Isinstance (a, int)
False
>>> Isinstance (B, str)
False
>>> Isinstance (B, int)
True

The following program shows how to use the isinstance function:

Copy codeThe Code is as follows:
Def displayNumType (num ):
Print num, 'is ',
If isinstance (num, (int, long, float, complex )):
Print 'a number of type: ', type (num). _ name __
Else:
Print 'not a number at all !!! '
DisplayNumType (-69)
DisplayNumType (9999999999999999999999999L)
DisplayNumType (565.8)
DisplayNumType (-344.3 + 34.4j)
DisplayNumType ('xxx ')

The code execution result is as follows:

Copy codeThe Code is as follows:
-69 is a number of type: int
9999999999999999999999999 is a number of type: long
565.8 is a number of type: float
(-344.3 + 34.4j) is a number of type: complex
Xxx is not a number at all !!!

6. len (object)-> integer

The len () function returns the length of the string and sequence.

Copy codeThe Code is as follows:
>>> Len ("aa ")
2
>>> Len ([1, 2])
2

7. pow (x, y [, z])

The pow () function returns the power of x as the base and y as the index. If the z value is given, this function calculates the y power value of x, which is the value of z modulo.

Copy codeThe Code is as follows:
>>> Print pow (2, 4)
16
>>> Print pow (2, 4, 2)
0
>>> Print pow (2.4, 3)
13.824

8. range ([lower,] stop [, step])

The range () function generates a list of sequential integers based on parameters.

Copy codeThe Code is as follows:
>>> Range (10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> Range (1, 10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> Range (1, 10, 2)
[1, 3, 5, 7, 9]

9. round (x [, n])

The round () function returns the rounding value of floating point x. If n is given, it indicates the number of digits rounded to the decimal point.

Copy codeThe Code is as follows:
>>> Round (3.333)
3.0
>>> Round (3)
3.0
>>> Round (5.9)
6.0

10. type (obj)

The type () function returns the data type of an object.

Copy codeThe Code is as follows:
>>> Type ()
<Type 'LIST'>
>>> Type (copy)
<Type 'module'>
>>> Type (1)
<Type 'int'>

11. xrange ([lower,] stop [, step])

The xrange () function is similar to range (), but xrnage () does not create a list, but returns an xrange object. Its behavior is similar to the list, however, the list value is calculated only when needed. when the list is large, this feature can save us memory.

Copy codeThe Code is as follows:
>>> A = xrange (10)
>>> Print a [0]
0
>>> Print a [1]
1
>>> Print a [2]
2

2. built-in type conversion functions
1. chr (I)

The chr () function returns the string corresponding to the ASCII code.

Copy codeThe Code is as follows:
>>> Print chr (65)
A
>>> Print chr (66)
B
>>> Print chr (65) + chr (66)
AB

2. complex (real [, imaginary])

The complex () function converts a string or number to a plural number.

Copy codeThe Code is as follows:
>>> Complex ("2 + 1j ")
(2 + 1j)
>>> Complex ("2 ")
(2 + 0j)
>>> Complex (2, 1)
(2 + 1j)
>>> Complex (2L, 1)
(2 + 1j)

3. float (x)

The float () function converts a number or string to a floating point number.

Copy codeThe Code is as follows:
>>> Float ("12 ")
12.0
>>> Float (12L)
12.0
>>> Float (1, 12.2)
12.199999999999999

4. hex (x)

The hex () function converts an integer to a hexadecimal number.

Copy codeThe Code is as follows:
>>> Hex (16)
'0x10'
>>> Hex (1, 123)
'0x7b'

5. long (x [, base])

The long () function converts numbers and strings into integers, and the base is an optional base.

Copy codeThe Code is as follows:
>>> Long ("123 ")
123L
>>> Long (11)
11L

6. list (x)

The list () function converts a sequence object to a list. For example:

Copy codeThe Code is as follows:
>>> List ("hello world ")
['H', 'E', 'l', 'l', 'O', '', 'w', 'O', 'R', 'l ', 'D']
>>> List (1, 2, 3, 4 ))
[1, 2, 3, 4]

7. int (x [, base])

The int () function converts numbers and strings into an integer. base is the optional base.

Copy codeThe Code is as follows:
>>> Int (3.3)
3
>>> Int (3L)
3
>>> Int ("13 ")
13
>>> Int ("14", 15)
19

8. min (x [, y, z...])

The min () function returns the minimum value of a given parameter, which can be a sequence.

Copy codeThe Code is as follows:
>>> Min (1, 2, 3, 4)
1
>>> Min (1, 2, 3), (2, 3, 4 ))
(1, 2, 3)

9. max (x [, y, z...])

The max () function returns the maximum value of a given parameter, which can be a sequence.

Copy codeThe Code is as follows:
>>> Max (1, 2, 3, 4)
4
>>> Max (1, 2, 3), (2, 3, 4 ))
(2, 3, 4)

10. oct (x)

The oct () function converts an integer to an octal number.

Copy codeThe Code is as follows:
>>> Oct (8)
'0'
>>> Oct (123)
'123'

11. ord (x)

The ord () function returns the ASCII or Unicode value of a string parameter.

Copy codeThe Code is as follows:
>>> Ord ("")
97
>>> Ord (u "")
97

12. str (obj)

The str () function converts an object to a printable string.

Copy codeThe Code is as follows:
>>> Str ("4 ")
'4'
>>> Str (4)
'4'
>>> Str (3 + 2j)
'(3 + 2j )'

13. tuple (x)

The tuple () function converts a sequence object to a tuple.

Copy codeThe Code is as follows:
>>> Tuple ("hello world ")
('H', 'E', 'l', 'l', 'O', '', 'w', 'O', 'R', 'l ', 'd ')
>>> Tuple ([1, 2, 3, 4])
(1, 2, 3, 4)

3. sequence processing functions
1. len (), max (), and min () in common functions can also be used in sequences.

2. filter (function, list)

When filter () is called, it applies a function to each item in the sequence, and returns all items in the return value of the function to the true value, so as to filter out all items that return the false value.

Copy codeThe Code is as follows:
>>> Def nobad (s ):
... Return s. find ("bad") =-1
...
>>> S = ["bad", "good", "bade", "we"]
>>> Filter (nobad, s)
['Good', 'we']

In this example, the nobad () function is applied to all items in the s sequence to filter out all items containing "bad.

3. map (function, list [, list])

The map () function applies a function to all items in the sequence and returns a list.

Copy codeThe Code is as follows:
>>> Import string
>>> S = ["python", "zope", "linux"]
>>> Map (string. capitalize, s)
['Python', 'zope ', 'linux']

Map () can also be applied to multiple lists at the same time. For example:

Copy codeThe Code is as follows:
>>> Import operator
>>> S = [1, 2]; t = [3, 2, 1]
>>> Map (operator. mul, s, t) # s [I] * t [j]
[3, 4, 3]

If a None value is passed, instead of a function, map () merges the corresponding elements in each sequence and returns the tuples. For example:

Copy codeThe Code is as follows:
>>> A = [1, 2]; B = [3, 4]; c = [5, 6]
>>> Map (None, a, B, c)
[(1, 3, 5), (2, 4, 6)]

4. reduce (function, seq [, init])

The reduce () function obtains the first two items in the sequence and passes them to the provided function. After obtaining the result, it obtains the next item in the sequence, passes the result to the function, and so on, until all items are processed.

Copy codeThe Code is as follows:
>>> Import operator
>>> Reduce (operator. mul, [2, 3, 4, 5]) # (2*3) * 4) * 5
120
>>> Reduce (operator. mul, [2, 3, 4, 5], 1) # (1*2) * 3) * 4) * 5
120
>>> Reduce (operator. mul, [2, 3, 4, 5], 2) # (2*2) * 3) * 4) * 5
240

5. zip (seq [, seq,...])

The zip () function combines the corresponding items in two or more sequences, returns them in the format of tuples, and stops processing all the items in the shortest sequence.

Copy codeThe Code is as follows:
>>> Zip ([1, 2, 3], [4, 5], [7, 8, 9])
[(1, 4, 7), (2, 5, 8)]

If the parameter is a sequence, zip () returns each item in the format of a mona1 group, for example:

Copy codeThe Code is as follows:
>>> Zip (1, 2, 3, 4, 5 ))
[(1,), (2,), (3,), (4,), (5,)]
>>> Zip ([1, 2, 3, 4, 5])
[(1,), (2,), (3,), (4,), (5,)]

4. Miscellaneous
The def statement is executed in real time. When it is run, it creates and assigns a new function object to a variable name. All Python statements are executed in real time, there is no process like independent Compilation Time

Because it is a statement, def can appear where any statement can appear-or even nested in other statements:

Copy codeThe Code is as follows:
If test:
Def fun ():
...
Else:
Def func ():
...
...
Func ()

You can assign a function to a different variable name and call it using the new variable name:

Othername = func ()
Othername ()
Create a function

The built-in callable function can be used to determine whether the function is callable:

Copy codeThe Code is as follows:
>>> Import math
>>> X = 1
>>> Y = math. sqrt
>>> Callable (x)
False
>>> Callable (y)
True

Use del statements to define functions:

Copy codeThe Code is as follows:
>>> Def hello (name ):
Return 'hello, '+ name + '! '
>>> Print hello ('World ')
Hello, world!
>>> Print hello ('gumby ')
Hello, Gumby!

Compile a function of the fibnacci series:

Copy codeThe Code is as follows:
>>> Def fibs (num ):
Result = [0, 1]
For I in range (num-2 ):
Result. append (result [-2] + result [-1])
Return result
>>> Fiber (10)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
>>> Fiber (15)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,144,233,377]

Assigning values to parameters in a function does not change the values of any external variables:

Copy codeThe Code is as follows:
>>> Def try_to_change (n ):
N = 'Mr. gumby'
>>> Name = 'Mrs. Entity'
>>> Try_to_change (name)
>>> Name
'Mrs. Entity'

Because strings (as well as tuples and numbers) cannot be changed, the parameters will not change. However, what will happen when a variable data structure such as a list is used as a parameter:

Copy codeThe Code is as follows:
>>> Name = 'Mrs. Entity'
>>> Try_to_change (name)
>>> Name
'Mrs. Entity'
>>> Def change (n ):
N [0] = 'Mr. gumby'

>>> Name = ['Mrs. Entity ', 'Mrs. action']
>>> Change (name)
>>> Name
['Mr. gumby', 'Mrs. action']

The parameter has changed, which is an important difference from the previous example.

Do not use the following function again:

Copy codeThe Code is as follows:
>>> Name = ['Mrs. Entity ', 'Mrs. action']
>>> N = name # Run the following command again to simulate parameter passing.
>>> N [0] = 'Mr. gumby' # change the list
>>> Name
['Mr. gumby', 'Mrs. action']

When two variables reference a list at the same time, they do reference a list at the same time. To avoid this situation, you can copy a copy of the list. When slicing is performed in the sequence, the returned slice is always a copy, so if you copy the slice of the entire list, you will get a copy:

Copy codeThe Code is as follows:
>>> Names = ['Mrs. Entity ', 'Mrs. action']
>>> N = names [:]
>>> N is names
False
>>> N = names
True

Changing n does not affect names:

Copy codeThe Code is as follows:
>>> N [0] = 'Mr. gumby'
>>> N
['Mr. gumby', 'Mrs. action']
>>> Names
['Mrs. Entity ', 'Mrs. th']
>>> Change (names [:])
>>> Names
['Mrs. Entity ', 'Mrs. th']

Keyword parameters and default values

Parameters can be ordered by providing the parameter name (but the parameter name and value must correspond ):

Copy codeThe Code is as follows:
>>> Def hello (greeting, name ):
Print '% s, % s! '% (Greeting, name)
>>> Hello (greeting = 'hello', name = 'World! ')
Hello, world !!

The most powerful keyword parameter is that the default value can be provided to the parameter:

Copy codeThe Code is as follows:
>>> Def hello_1 (greeting = 'hello', name = 'World! '):
Print '% s, % s! '% (Greeting, name)

>>> Hello_1 ()
Hello, world !!
>>> Hello_1 ('greetings ')
Greetings, world !!
>>> Hello_1 ('greeting ', 'Universe ')
Greeting, universe!

If you want greeting to use the default value:

Copy codeThe Code is as follows:
>>> Hello_1 (name = 'gumby ')
Hello, Gumby!

It is not difficult to implement the function by providing any number of parameters:

Copy codeThe Code is as follows:
>>> Def print_params (* params ):
Print params

>>> Print_params ('testing ')
('Testing ',)
>>> Print_params (1, 2, 3)
(1, 2, 3)

Mixed common parameters:

Copy codeThe Code is as follows:
>>> Def print_params_2 (title, * params ):
Print title
Print params

>>> Print_params_2 ('params: ', 1, 2, 3)
Params:
(1, 2, 3)
>>> Print_params_2 ('Nothing :')
Nothing:
()

The asterisk indicates "collecting other location parameters". If no element is provided for collection, params is an empty tuples.

However, keyword parameters cannot be processed:

Copy codeThe Code is as follows:
>>> Print_params_2 ('hmm... ', something = 42)
Traceback (most recent call last ):
File "<pyshell #112>", line 1, in <module>
Print_params_2 ('hmm... ', something = 42)
TypeError: print_params_2 () got an unexpected keyword argument 'something'

Try "**":

Copy codeThe Code is as follows:
>>> Def print_params (** params ):
Print params

>>> Print_params (x = 1, y = 2, z = 3)
{'Y': 2, 'x': 1, 'z': 3}
>>> Def parames (x, y, z = 3, * pospar, ** keypar ):
Print x, y, z
Print pospar
Print keypar

>>> Parames (1, 2, 3, 5, 6, 7, foo = 1, bar = 2)
1 2 3
(5, 6, 7)
{'Foo': 1, 'bar': 2}
>>> Parames (1, 2)
1 2 3
()
{}
>>> Def print_params_3 (** params ):
Print params

>>> Print_params_3 (x = 1, y = 2, z = 3)
{'Y': 2, 'x': 1, 'z': 3}
>>> # The returned data is a dictionary rather than a tuples.
>>># Combination '#' and '##'
>>> Def print_params_4 (x, y, z = 3, * pospar, ** keypar ):
Print x, y, z
Print pospar
Print keypar

>>> Print_params_4 (1, 2, 3, 5, 6, 7, foo = 1, bar = 2)
1 2 3
(5, 6, 7)
{'Foo': 1, 'bar': 2}
>>> Print_params_4 (1, 2)
1 2 3
()
{}


Different python methods and functions

Method
A function which is defined inside a class body. if called as an attribute of an instance of that class, the method will get the instance object as its first argument (which is usually called self ).
In Chinese, the method is equivalent to a class function. The first parameter is self.
This is in the official document. Read more documents

Getting started with python function value passing,

In the figure on the right, put the definition of the function file_path in front of get_Excel_Value_S.
The call to file_path () in this figure appears in the definition of the function. At this time, the file_path function is not defined.
The left file_path () appears in the code of the get_Excel_Value_S function. It is executed only when the last print statement calls the function. At this time, both functions are defined and no error is reported. However, for function definition, the default value of the parameter must be determined after the definition. Therefore, the right image is called before file_path is defined, and an error is returned.

Related Article

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.