Python based learning four

Python based learning four

1. Built-in functions

help () function: to view the use of built-in functions.

help(abs)

the isinstance () function: for determining the type of the variable.

isinstance (x, (int, float)) # determines whether the variable x is int or float, returns a Boolean value

2. Custom Functions

(1) Basic Format


DEF [function name] (parameter):

Statement block

return return value


Custom function to run as long as the end of the function returns a return statement i.e., the parameter passed to the plurality of values ​​that can be returned when the returned value is a plurality of essentially returns a tuple. The return value can be empty.

The pass statement: occupying the role of the statement can continue. That time has not yet want to write about what you can skip using the pass statement.

By the isinstance () function can be used to exclude wrong type.


DEF [function name] (x):

​ if not isinstance(x,(int,float)):

​ raise TypeError('bad operand type')

Statement block


(2) Parameters

Default parameters: When setting the parameters, which can be given a default value, when the filling space, which is the default value default. The default parameter must be placed behind the mandatory parameters.

It should be noted that small changes placed in the rear as the default parameters can reduce call functions trouble. Only need to pass a special object, modify the corresponding parameters. Define default parameters to keep in mind one thing: the default parameters must point to the same objects!

Variable parameters: the number of variable parameters, before the parameters with an asterisk "*." When the incoming parameters, a list of allowed incoming tuple or the like

Keyword arguments: the former parameter plus two asterisks "**." Need to write when you call the 'keyword' = 'content'

Named keyword arguments: the following format:


DEF [parameter name] (mandatory parameter, *, parameter 1)


In the parameters of the asterisk is regarded as a named keyword arguments, if the function definition have a total of variable parameters placed in front named keyword arguments. You can no longer use an extra asterisk separated.

When calling the function, parameter name must be passed in order keyword arguments.


[Parameter Name] (mandatory parameter, the parameter 1 = 'content')


3. recursive function

It calls itself a function within a function that is recursive functions.

(1) Optimization of tail recursion

To prevent the stack overflow, optimization calculation using recursive manner.

Tail recursion: When the function returns, calls itself itself, and, return statement can not contain expressions.

Analysis examples: Tower of Hanoi


def han(n,a,b,c):

​ if n=1:

​ print(a,'-->',c)

​ else:

​ han(n-1,a,c,b)

​ print(a,'-->',c)

​ han(n-1,b,a,c)


Guess you like

Origin www.cnblogs.com/ljl233/p/12230565.html