python base - Function (1)

What is the function?

Tissue function is good, reusable, code segments used to implement a single, or the associated function

 

1. Function names must begin with a letter

DEF a2_33 >>> ():
... # Pass Pass means no nothing, just a placeholder
...
>>> a2_33 () # function calls the function name in parentheses
>>>

Count the number of letters: Exercises

>>> def count_letter(s):
...     result = 0
...     for i in s:
...         if i >='a' and i <='z':
...             result +=1
...     return result
...
>>> count_letter("1a2Drty")
4

Exercise: Statistics sentence, the number of digits

>>> def f(s):
...     result =0
...     for i in s:
...         if i >='0' and i <= '9':
...             result +=1
...     return result
...
>>> f("1a2b3c4d")
4

Transfer function parameter
>>> DEF the Add (A, B):
... return A + B
...
>>> the Add (1,2)
. 3

DEF the Add (A, B):
    IF the isinstance (A, (int, a float, Complex)) and the isinstance (B, (int, a float, Complex)): # Analyzing Parameter Type
        return a + b # return a short circuit function, it is not write the else
    Print ( "One of the Parameters TWO IS A Number The not of the type!")
    return None
Print (the Add ( "A", 2))

 

Global and local variables

>>> n = 1 # functions defined externally variable called global variables
>>> DEF FUNC ():
... # 2 = n-defined variables inside a function, called a local variable, a function, local variable do not come into force
... n-return
...
>>> FUNC ()
2
>>> Print (n-)
. 1
>>> FUNC = 10
>>> FUNC ()
Traceback (MOST Recent Last Call):
  File "< stdin> ", Line 1, in <Module>
TypeError: 'int' IS not a Callable Object # can not be re-assigned to a function to avoid an error
>>>

 

 Required parameters: essential

Optional parameters: when there are defaults will not fill with default values, use the value passed when no default, default values ​​must be placed behind the non-default values

DEF the Add >>> (A, B = 100):
... return A + B
...
>>> the Add (. 1) # default value
101
>>>

>>> add(1,11)#传值
12
>>>

>>> add (b = 1, a = 11) # value parameters name to
12
>>>

DEF the Add >>> (A = 100, B):
... return A + B
...
  File "<stdin>", Line. 1
SyntaxError: non-default argument default argument # Default Follows a non-default values in front, error

 

Return multiple parameters

>>> def times_ten_bigger(a,b):
...     return a*10,b*10
...
>>> a,b=times_ten_bigger(1,2)
>>> print(a)
10
>>> print(b)
20
>>>

Named parameters manner by value

 

def times_ten_bigger(a,b,c=100):
    return a*10,b*10,c*10

print(times_ten_bigger(c=5,b=1,a=2))
 
 
1 can be written

>>> n=1
>>> def func():
...     return n+1
...
>>> func()
2
>>>

 

2 can be written

>>> n=1
>>> def func():
...     n=2
...     return n
...
>>> func()
2
>>>
 
3 can not write
>>> n=1
>>> def func():
...     n+=1
...     return n#不知道返回的是哪一个n
...
>>> func()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in func
UnboundLocalError: local variable 'n' referenced before assignment

 

3 can be written instead of global variables

>>> n=1
>>> def func():
...     global n
...     n+=1
...     return n
...
>>> func()
2
>>> n
2
>>>

 

4 can be written

. 1 = n->>>
>>> DEF FUNC (A):
... = A + A. 1
... A return
...
>>> FUNC (n-) #n is passed as a parameter
2
>> > n-
. 1
>>>

 

n =[]
def func(a):
    a.append(1)

print(func(n))
print(n)
 
 
 
n="abc"
def func(a):    
    a=a+"d"
    


print(func(n))
print(n)
 

 

Principle 1:
If you pass a parameter is a variable a, this variable is a variable types
(list, dict, set)
then the internal function of all operating results for this parameter will affect the
parameter value outside of

Principle 2:
If you pass is a variable parameter a, the variables are immutable type ()
(string, integer, decimal)
then the internal function of the result of this operation for all the parameters are not influenced by external variables

 

Variable parameters, * c, is stored as the ancestral

def add(a,b,*c):
    print(type(c))
    print(c)
add(1,2,3,4,5)
add(1,2,3,4,5,6,7,8)
 
Exercise: all of the values ​​of the above function, for obtaining the sum and returns.
def add(a,b,*c):
    result =a+b
    for i in c:
        result+=i
    return result
print(add(1,2,3,4,5))
 
** variable, as dictionary
Exercise: all of the values ​​of the above function, for obtaining the sum and returns.
def add(a,b,**c):
    result = a+b
    for i in c.values():
        result +=i
    return result
print(add(1,2,c=3,d=4,e=5))
 

 

Exercise:

def add(a,b,*c,**d):#*要放在**后面
    result =a+b
    for i in c:
        result +=i
    for i in d.values():
        result +=i
    return result

print(add(1,2,3,4,c=5,d=6,e=7))

Function defaults

>>> def add(a,b=100):
...     return a+b
...
>>> print(add(10))
110
>>>

 

Function passed in parameter is immutable, no effect on the external variables

Pass by value. (Not transfer the memory address corresponding to the variable)

Function argument passed to a variable, the variable will affect the external

Pass-by-reference. (Pass variables to memory address)

>>> a=100
>>> def f(a):
...     a+=1
...     return a
...
>>> f(a)
101
>>> a =[]
>>> def f(a):
...     a.append(1)
...     return a
...
>>> f(a)
[1]
>>> a
[1]
>>>

 

 

Global Variables

>>> a =100
>>> def f():
...     global a
...     a+=1
...     return a
...
>>> a
100
>>> f()
101
>>>

 

 

The variable parameters are passed

>>> def f(a,b,*arg):
...     print(type(arg))
...     for i in arg:
...         print(i)
...
>>> f(1,2,3)
<class 'tuple'>
3
>>> f(1,2,3,4)
<class 'tuple'>
3
4
>>> f(1,2,3,4,5,6,7)
<class 'tuple'>
3
4
5
6
7
>>>

 

 

Exercise:

Write a function using a variable parameter calculation of all the parameters and functions

>>> def f (a, b, * arg): # variable parameter to be placed after the fixed parameters
... Result = 0
... Result = A + B
... I in for Arg:
... Result = I +
... return Result
...
>>> F (1,2,3,4,5)
15

 
>>> def f(*arg):
...     for i in arg:
...         print(i)
...
>>> f(1,2,3,4,5)
1
2
3
4
5
>>>
 
 
 
 
 
>>> def f (a,b,**kw):
...     print(type(kw))
...     for k,v in kw.items():
...         print(k,v)
...
>>> f(a=1,b=2,c=3)
<class 'dict'>
c 3
>>> f(1,2,a=3,b=4,c=5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: f() got multiple values for argument 'a'   #传参重复,a已经存在
>>> f(1,2,c=3,d=4,e=5)
<class 'dict'>
c 3
d 4
e 5
>>>
 
 
 
>>> def func(a,b):
...     print(a,b)
...
>>> func(b=1,a=2)
2 1
>>>
 

 

 

 
* Arg: indicates the plurality of non-variable conversion for a named parameter tuples
** kw: the representation of multiple variable named parameters turn to a dictionary

Guess you like

Origin www.cnblogs.com/wenm1128/p/11610313.html