day006-python function

First, the definition of the function   def function name ():

    Function body Code

  Example:
  #define function
  DEF In Email ():
    Print ( 'Send In Email')
  # call to a function
  In Email ()

Second, the function return value

  DEF In Email ():
    Print ( "Send In Email")
    return "transmission success" # no return, default return None

  RET = in Email () function return back # what value, ret return value is equal to
  print (ret)
Note: upon return, the return of the internal function code encounters no longer performed.

Third, the general parameters of the function

  def email (address): #address formal parameters
  Print (address)
  return True

  ret = email ('[email protected] ') # call execution by value, the actual parameter
  # parameter passing, the default value is based on transfer order can also be specified parameter arguments passed, it may not order

four functions the default parameters

  # Note: there is a default value for a parameter on the back
  def email (name, address = " [email protected]"): # name, address formal parameters, address has a default value [email protected]
  Print (name, address)
  return True

five, the dynamic parameters of the function

1) simple dynamic parameters
# Note: * number plus one, can be in the form of dynamic parameters, the conversion element group; ** plus two numbers, the conversion into a dictionary
  def email (* addr, ** address):
    Print (addr)
    Print (address)

  email (11, 22, 33, k1 = 123, k2 = 456) # dynamic function parameters, a plurality of parameters can be passed
  Results:
  (11,22,33)
  { 'K1': 123, 'K2': 456 }

2) is passed a list of dynamic parameters, a dictionary or tuples
  2.1) passed argument list
    DEF F1 (* args):
      Print (args)

    li = [11,22,33,44] #列表
    f1(li)         #结果为[11,22,33,44]
    f1(*li)        #结果为(11,22,33,44),注意在传入实参时,加入*号
  2.2)实参传入字典
    def f2(**kwargs):
      print(kwargs)

    dic = {'k1':789} #传入字典
    f2(dic)           #结果报错
    f2(**dic)        #结果为{'k1':789},注意在传入实参时,加入**号

六、全局变量、局部变量

  P = "python"         #p为全局变量,变量名一般大写,可以共享使用

  def func():
    a = 123          #a 为局部变量,变量名一般小写,只能在func()函数中使用
    #如果在函数内想修改全局变量,则需要使用关键字global
    global P
    P = "java"            #全局变量P的值被修改为"java"

    print(a)          #结果为123
    print(P)        #func()函数可以使用全局变量

Guess you like

Origin www.cnblogs.com/june-L/p/11546438.html