The function of the introductory article of Python

Source: Internet
Author: User
Tags mul ord
The function of Pythond is written by a new statement, that is, Def,def is an executable statement--the function does not exist until Python has run def.

Functions are passed by assignment, and parameters are passed to the function by assignment

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

The code is as follows:


def function_name (arg1,arg2[,...]):
Statement
[Return value]

The return value is not required, and if there is no return statement, Python returns the value none by default.

Naming rules for function names:

The function name must begin with an underscore or letter and can contain any combination of letters, numbers, or underscores. Cannot use any punctuation marks;

Function names are case-sensitive.

The function name cannot be a reserved word.

Python uses the concept of namespaces to store objects, which are the areas where objects are scoped and different objects exist in different scopes. The following are the scope rules for different objects:

Each module has its own global scope.

The object defined by the function is a local scope, valid only within the function, and does not affect objects in the global scope.

An Assignment object is a local scope unless declared using the Global keyword.

The LGB rule is Python's rule for finding a name, and here's the LGB rule:

1. Most names are referred to in three scopes: first local, second global (global), and again built-in (build-in).

The 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.

The code is as follows:


#没用global时的情况
>>> name= "Jims"
>>> def set ():
... name= "Ringkee"
...
>>> Set ()
>>> Print Name
Jims

#使用global后的情况
>>> name= "Jims"
>>> def set1 ():
... global Name
... name= "Ringkee"
...
>>> Set1 ()
>>> Print Name
Ringkee

3. The ' Global ' declaration maps the name of the assignment to the scope of a module containing it.

The parameter of a function is the bridge between the function and the external communication, which can receive the value passed by the outside. The rules for parameter passing are as follows:

4. Assigning a value to a parameter name in a function does not affect the caller.

The code is as follows:


>>> a=1
>>> def Test (a):
... a=a+1
.. print a
...
>>> Test (a)
2
>>> A
1 # The value of a does not change

5. Changing a Variable object parameter in a function affects the caller.

The 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]
>>> A
1
>>> b
[4, 2] # B value has been changed

Parameters are object pointers and do not need to define the type of object being passed. Such as:

The code is as follows:


>>> def Test (A, B):
... return A+b
...
>>> Test #数值型
3
>>> Test ("A", "B") #字符型
' AB '
>>> test ([12],[11]) #列表
[12, 11]

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

def function (Arg=value)
Tuple (tuples) parameter:

def function (*arg)
Dictionary (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 after the connection parameter and the default parameter.

The dictionary parameter must be defined last.

1. Common functions
1.abs (x)

ABS () returns the absolute value of a number. If the plural is given, the return value is the modulus of the complex number.

The 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 an object can be called, or 1 (true) if it is possible, otherwise 0 (false) is returned. Callable objects include functions, methods, code objects, classes, and class instances that already have a call method defined.

The code is as follows:


>>> a= "123"
>>> Print callable (a)
0
>>> Print callable (CHR)
1

3.CMP (x, y)

The CMP () function compares x and y two objects and returns an integer based on the result of the comparison, if x y, returns 1 if X==y returns 0.

The code is as follows:


>>>a=1
>>>b=2
>>>c=2
>>> Print CMP (A, B)
-1
>>> Print CMP (b,a)
1
>>> Print CMP (B,C)
0

4.divmod (x, y)

The Divmod (x, y) function completes the division operation, returning the quotient and remainder.

The 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

The 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 the use of the Isinstance function:

The 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 @ all!!! '
Displaynumtype (-69)
Displaynumtype (9999999999999999999999999L)
Displaynumtype (565.8)
Displaynumtype ( -344.3+34.4J)
Displaynumtype (' xxx ')

The result of the code operation is as follows:

The 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 isn't a number at all!!!

6.len (object), Integer

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

The code is as follows:


>>> len ("AA")
2
>>> Len ([up])
2

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

The POW () function returns a power of x, and y as the exponent. If the z-value is given, the function calculates the value of the Y-power of x being the z-modulo.

The 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 sequential list of ordered integers by parameter.

The 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 the floating-point number x, if given an n value, that represents the digits rounded to the decimal point.

The 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 the object.

The code is as follows:


>>> type (a)

>>> type (copy)

>>> Type (1)

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

The xrange () function is similar to range (), but xrnage () does not create a list, but instead returns a Xrange object that behaves like a list, but calculates the list value only when it is needed, which saves us memory when the list is large.

The code is as follows:


>>> A=xrange (10)
>>> Print A[0]
0
>>> Print A[1]
1
>>> Print a[2]
2

2. Built-in type conversion function
1.CHR (i)

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

The code is as follows:


>>> Print Chr (65)
A
>>> Print Chr (66)
B
>>> print Chr (+CHR) (66)
Ab

2.complex (Real[,imaginary])

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

The 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 into a floating point.

The code is as follows:


>>> Float ("12")
12.0
>>> Float (12L)
12.0
>>> Float (12.2)
12.199999999999999

4.hex (x)

The hex () function converts integers to hexadecimal numbers.

The code is as follows:


>>> Hex (16)
' 0x10 '
>>> Hex (123)
' 0x7b '

5.long (X[,base])

The long () function converts numbers and strings to grow integers, and base is an optional cardinality.

The code is as follows:


>>> Long ("123")
123L
>>> Long (11)
11L

6.list (x)

The list () function converts a sequence object to a list. Such as:

The 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 an optional cardinality.

The 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 the given parameter, which can be a sequence.

The code is as follows:


>>> min (1,2,3,4)
1
>>> min ((2,3,4))
(1, 2, 3)

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

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

The code is as follows:


>>> Max (1,2,3,4)
4
>>> Max ((+), (2,3,4))
(2, 3, 4)

10.OCT (x)

The OCT () function converts an integer given to an octal number.

The code is as follows:


>>> Oct (8)
' 010 '
>>> Oct (123)
' 0173 '

11.ord (x)

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

The code is as follows:


>>> Ord ("a")
97
>>> Ord (U "a")
97

12.str (obj)

The STR () function converts an object into a printable string.

The 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.

The 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 a common function are also used for sequences.

2.filter (Function,list)

When you call filter (), it applies a function to each item in the sequence and returns all items when the function returns True, thereby filtering out all items that return false values.

The code is as follows:


>>> def Nobad (s):
... return s.find ("bad") = =-1
...
>>> s = ["bad", "good", "bade", "we"]
>>> Filter (Nobad,s)
[' Good ', ' we ']

This example filters out all items that contain "bad" by applying the Nobad () function to all the items in the S sequence.

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

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

The 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. Such as:

The code is as follows:


>>> Import operator
>>> s=[1,2,3]; t=[3,2,1]
>>> map (operator.mul,s,t) # S[i]*t[j]
[3, 4, 3]

If you pass a none value instead of a function, map () merges the corresponding elements in each sequence and returns that tuple. Such as:

The 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, passes it to the provided function, obtains the result, and then passes the next item in the sequence, along with the result, to the function, and so on, until all items have been processed.

The code is as follows:


>>> Import operator
>>> reduce (operator.mul,[2,3,4,5]) # (2*3)
120
>>> reduce (operator.mul,[2,3,4,5],1) # ((1*2)
120
>>> reduce (operator.mul,[2,3,4,5],2) # ((2*2)
240

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

The zip () function merges the corresponding items in two or more sequences and returns them in a tuple format, stopping after all items in the shortest sequence have been processed.

The code is as follows:


>>> zip ([1,2,3],[4,5],[7,8,9])
[(1, 4, 7), (2, 5, 8)]

If the argument is a sequence, zip () returns each item in a tuple format, such as:

The 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. Other
The DEF statement executes in real time, and when it runs, it creates and assigns a new function object to a variable name, and all of the Python statements are executed in real time, without a process like a separate compile time

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

The 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 with a new variable name:

Othername=func ()
Othername ()
Create a function

The built-in callable function can be used to determine whether a function can be called:

The code is as follows:


>>> Import Math
>>> x=1
>>> y=math.sqrt
>>> Callable (x)
False
>>> Callable (Y)
True

Use the DEL statement to define the function:

The code is as follows:


>>> def Hello (name):
Return ' Hello, ' +name+ '! '
>>> Print Hello (' world ')
Hello, world!.
>>> Print hello (' Gumby ')
Hello, gumby!.

Write a fibnacci sequence function:

The code is as follows:


>>> def fibs (num):
result=[0,1]
For I in Range (num-2):
Result.append (Result[-2]+result[-1])
return result
>>> fibs (10)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
>>> fibs (15)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]

Assigning a value to a parameter within a function does not change the value of any external variable:

The code is as follows:


>>> def try_to_change (n):
N= ' Mr.gumby '
>>> name= ' mrs.entity '
>>> Try_to_change (name)
>>> Name
' Mrs.entity '

Because strings (and tuples and numbers) are immutable, they do not change when parameters are made, but what happens if you use a mutable data structure such as a list as a parameter:

The 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.thing ']
>>> Change (name)
>>> Name
[' Mr.gumby ', ' mrs.thing ']

Parameters have changed, which is the important difference from the previous example

The following do not use the function again:

The code is as follows:


>>> name=[' mrs.entity ', ' mrs.thing ']
>>> n=name #再来一次, simulation of the transfer of parameter behavior
>>> n[0]= ' Mr.gumby ' #改变列表
>>> Name
[' Mr.gumby ', ' mrs.thing ']

When 2 variables refer to a list at the same time, they do refer to a list at the same time, to avoid this, you can copy a copy of a list, and when you slice in a sequence, the slice returned is always a copy, so you copy the entire list of slices, and you get a copy:

The code is as follows:


>>> names=[' mrs.entity ', ' mrs.thing ']
>>> n=names[:]
>>> N is names
False
>>> N==names
True

Changing n At this time does not affect the names:

The code is as follows:


>>> n[0]= ' Mr.gumby '
>>> N
[' Mr.gumby ', ' mrs.thing ']
>>> names
[' mrs.entity ', ' mrs.thing ']
>>> change (names[:])
>>> names
[' mrs.entity ', ' mrs.thing ']

Keyword parameters and default values

The order of the parameters can be given by giving the parameter a name (but the parameter name and value must correspond):

The code is as follows:


>>> def hello (greeting, name):
print '%s,%s! '% ( Greeting, name)
>>> Hello (greeting= ' hello ', name= ' world! ')
hello,world!!

The most powerful thing about keyword parameters is that you can provide default values for parameters in Parameters:

The 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:

The code is as follows:


>>> hello_1 (name= ' Gumby ')
hello,gumby!

You can provide any number of parameters to the function, and it is not difficult to implement them:

The code is as follows:


>>> def print_params (*params):
Print params

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

Mix common parameters:

The code is as follows:


>>> def print_params_2 (title,*params):
Print title
Print params

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

The asterisk means "collect the rest of the positional parameters", and if you do not provide any elements for collection, the params is an empty tuple

However, you cannot handle keyword parameters:

The code is as follows:


>>> print_params_2 (' Hmm ... ', something=42)
Traceback (most recent):
File " ", line 1, in
Print_params_2 (' Hmm ... ', something=42)
Typeerror:print_params_2 () got an unexpected keyword argument ' something '

Try using "* *":

The 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
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 3
()
{}
>>> def Print_params_3 (**params):
Print params

>>> Print_params_3 (x=1,y=2,z=3)
{' Y ': 2, ' X ': 1, ' Z ': 3}
>>> #返回的是字典而不是元组
>>> #组合 ' # ' and ' # # '
>>> def print_params_4 (x,y,z=3,*pospar,**keypar):
Print x, y
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 3
()
{}

  • 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.