Fourth Lecture: function (on)

Function (on)

First, the function definition:

1, functions to define rules:
Custom function, you need to meet some rules, otherwise the compiler will not recognize.
(1) Function block def keyword beginning, followed by the function names and identifiers in parentheses ().
(2) any incoming arguments and parameters must be placed in parentheses. It is written in parentheses parameter.
The first statement (3) function can be selectively used documentation string - for storing function instructions.
(4) the starting function contents colon, and the body have indented function.
(5) return [expression] End function, selectively returns a value to the caller. With no expression
The return is equivalent to return None.
 
2, the syntax:
def functionname( parameters ):
"Function _ docstrings"
  function_suite
return[expression]
By default, the parameter name and the parameter value is defined as a function of the order of declaration match up.

 

Second, the parameters of the function

1, no function parameter:

def sayHello():
  print 'Hello World!'
sayHello ()

 

2, reference function

When calling a function in python, parameters include the following types:
  • Mandatory parameter
  • Named parameters
  • The default parameters
  • Variable-length parameters

2.1, there is a reference function - essential parameters:

2.1.1, the necessary parameters - parameters passed immutable (string, number)

Note: If the function is a received immutable object (such as numbers, characters, or tuples) of the parameters, this time is to pass through the object "by value", at this time if you want to change the value of the original variables, these variables may be declared as global variables
 
 
1 ,, the number of functions to pass parameters with different parameters will be given.
def info(name, age, tel) :
  print "name:" + name + ", age:" + str(age) +", tel:" + tel
 
info('jack', 20,'13567867878')   
info ( 'jack', 20, ') # pass number of different parameters, being given
 
2 ,, the local and global variables:
Local variables: the parameters have, the value passed to the function
Example 1:
DEF changeNum (num): 
num + =. 1
Print U 'self-defined function num =', num

num = 10
changeNum (num)
Print U 'after the function call num =', num

run results:
custom function in num =. 11
NUM = 10 after the function call

Global variables: the no reference, can change the value of the function. If the changes in the global variables function, and does not pass parameters plus global variable declarations global
Example 2:
changeNum DEF (): 
Global NUM
NUM = +. 1
Print U 'self-defined function = NUM', NUM

NUM = 10
changeNum ()
Print U 'function call after NUM =', num
 
To avoid confusion global and local variables error, it is recommended:
a, variable names within the function and global variable names do not duplicate names
b, the use of global variables, use the global declare global variables within a function
 
 

2.1.2, the essential parameters - pass variable objects (a list or dictionary)

1, if the function is to receive a variable object (such as dictionaries or lists) parameters, this is the time pass by "reference" parameter (in fact, this is ultimately pass the values ​​passed, just point to a memory address space value)
 
Example:
chaneList DEF (list1): 
list1.append ( 'for newstr')
Print U 'function in the list1:', list1

list1 = [l, 2,3]
Print U 'before the function call list1:', list1
chaneList (list1)
print u 'after calling function list1:', list1

run results:
call list1 before the function: [1, 2, 3]
function in list1: [1, 2, 3, 'for newstr']
list1 after calling function: [1, 2, 3, ' newstr']
 
2, the variable transfer parameters are the default target, change the value of object
Example:
add_end DEF (L = []): 
L.append ( 'the END')
return L
Print add_end ([l, 2,3]) # pass non-null reference, calling normal
print add_end ([ 'x', 'y', 'z']) # pass non-null reference, calling normal
print add_end () # default parameters of the first passage, calling normal
print add_end () # default parameters of the second pass, the list has to remember the previous value, the call is not normal
print add_end () # third passage default parameters has remember the last value list, call abnormal

operating results:
[. 1, 2,. 3, 'the END']
[ 'X', 'Y', 'Z ',' the END ']
[' the END ']
[' the END ',' the END ']
[' the END ',' the END ',' the END ']
Description:
a, Python function defined at the time, the default value of the parameter L was calculated out, i.e., []
B, the default parameters because L is a variable that points to the object [], every time the function is called, if the changed content of L, then the next call, the default parameters changed, and is no longer a function definition [] a.
c, Note: The definition of default parameters to keep in mind one thing: the default parameters must point to the same objects!
 
3, the function should check the data type of parameter passing, to avoid chaos call:
def my_abs(x):
if not isinstance(x,(int,float)):
raise TypeError('bad operand type')
if x>=0:
return x
else:
return -x

print my_abs(-1)
print my_abs('x')
 

2.2, there is a reference function - named arguments

Note: non-named parameter must be named after the argument, otherwise it will be reported when the mass participation SyntaxError: Error non-keyword arg after keyword arg's.
 
Example:
SUM DEF (A, B, C): 
SUM = A + B * 100 + 10 * C
return SUM

Print '= SUM', SUM (. 3, B = 2, C =. 5)

Run Results:
SUM = 325

 

2.3, there is a function parameter - the default parameters

1. Note: The default value must be placed in the rearmost no default parameters, otherwise it will error. This is because the value assigned to parameter is assigned according to the position and

Example:

say DEF (Message, Times =. 1): 
return Message * Times
( '! Hello World') say Print
Print say (U 'Come on!', 3)

Run Results:
Hello World!
Come on! Come on! Come on!

2, specify multiple defaults to the assignment by naming, also known as the key parameter assignment (using the name assignment, instead of the position assignment)

Example:

def func(x,y=4,z=6):
print 'x is',x
print 'y is',y
print 'z is',z

func(3,5)
print "-"*15
func(25,z=8)
print "-"*15
func(z=20,x=100)

运行结果:
x is 3
y is 5
z is 6
---------------
x is 25
y is 4
z is 8
---------------
x is 100
y is 4
z is 20

2.4, there is a function parameter - variable length parameter (tuple or dictionary as a parameter)

1, variable length parameters - used as a parameter tuple

Example: Function incoming tuple parameters, calculate the sum of the parameter passing.

SUM DEF (A, B *): # * indicates the value passed in as an incoming tuple

A = SUM
: for I in b
# # I Print print all the values in the tuple b
SUM = I +
return SUM

when print 'sum =', sum ( 1,2,3,4,5) # pass plurality of values , as the value of a first value, the value of b for all the following values for a tuple (2,3,4,5)

operating results:
SUM = 15

 

2, variable length parameter - use a dictionary as an argument

Example: Print out incoming Dictionary

def sum (** kw): # ** means that the incoming value as the dictionary passed 
for K, V in kw.items ():
Print K, V

SUM (A =. 1, B = 2, C =. 4, D = 6)

run results:
A. 1
C. 4
B 2
D 6

3, variable length parameters - and tuple, and dictionary parameters (parameters as a function of the * and **)

Example:

printInfo DEF (A, B = 2, TUP *, ** DIC): 
Print A
Print B
Print TUP
Print DIC

printInfo (3,4,5,6,2, X =. 1, Y = 2)

result:
. 3
. 4
(. 5,. 6, 2)
{ 'Y': 2, 'X':. 1}

Description:

In accordance with the parameter assignment order, a = 2, c = 3,4 and 5 in the presence tuple tup, x = 1, y = 2 in the presence of dic dictionary.
It can be seen, when the mass transfer parameters and dictionary reference tuples distinction:
Tuple just pass the same general parameters, but the dictionary is a key element of the composition, so we need to pass key-value expressions when mass participation.

 

 

 

 

 

 

 

 

 

 

 
 
 

Guess you like

Origin www.cnblogs.com/wenxiacui/p/10927769.html