Python3.x basic learning-function usage

Function usage

 

Function parameter type

Immutable type parameters: numeric, string str, tuple tuple. 
Variable type:
a is immutable in the list and dictionary dict functions. Fun (a) modifies the value of a internally, but only modifies another copied object without affecting a itself.
1. Passing immutable type parameters will not affect the parameter itself
2. Passing variable type parameters will affect the parameter itself

# Immutable parameter type 
a = 1 print (id (a)) # 2009628784 def func(a): a= 10 print(a,id(a)) func(a) # 20 2009629392 def func(a): a= 1 print(a,id(a)) func(a) # 1 2009628784 print(a,id(a)) # 1 2009628784

 

# Variable parameter type 

B = [10,20 ]
 Print (ID (B))
 # 2324968580360


def func(b):
    b.append(30)
    print(id(b))


func(b)
#2324968580360
print(b,id(b))
# [10, 20, 30] 2324968580360

 Function parameters (mandatory parameters, default parameters, optional parameters, keyword parameters)

 

# Required parameters

def func1(x):
    return x*x

func1(2)

#4

#Default parameter,
#Note: The default parameters must be placed after the mandatory parameters 
# Defects:
def funcx(L=[]):
    L.append ( " The End " return L funcx () # In the function definition, the address specified by the default parameter L has been determined. Each call will change the content of L
  


 
 

def func2(x,y=10):
    return x*y

func2(3)
# 30

func2(3,5)
# 15 

optional parameter

def func3 (* nmbers):
  sum = 0
  for i in numbers:
    sum = sum + i * i
  return sum

func3 ([1,2,3])
# 14

keyword parameter

def func4 (name, * * kwargs):
  print ("data:", kwargs)

 

 

recursive function

Recursive function If a function calls itself internally, this function is a recursive function. 
Conditions for using recursive functions:
1. Must leave the exit
2. Call your own

case1:
# Recursive function evaluation. 3 .... * 2 *. 1. 7 * * *. 8. 9 * 10 
DEF FUNC (X):

    if x==1:
        return x
    return x*func(x-1)

print(func(10))

#3628800

 

case2:

# Expand the list all 

lst1 = [1,2, [3,4, [5, [6, [7], 8,9]], 10], 11,12,13 ] lst2 =[] DEF FUNC (LST1): for i in LST1: IF isinstance (i, List): # if list is executed FUNC (i) FUNC (i) the else : lst2.append (i) # If it is not put into lst2 element list func(lst1) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,13]

case3:

# Use the recursive function to find the Fibonacci sequence 
#
1 1 # 2 2 # 3 2 + 1 = 3 # 4 3 + 2 = 5 # ... # nf (n-1) + f (n-2) def func(n): if n==1 or n==2: return n return func(n-1)+func(n-2) print(func(5)) # 8

case3:

A frog can jump 1 or 3 or 7 or 10 steps at a time. Q: There are n steps. How many ways can a frog jump up?
1-2 1 n <= 2 f (n) = 1
3    2  f(2)+f(0)=2
4   2+1=3  f(3)+f(1)=4
5   3+1=4
6  4+2=6
...
n     f(n-1)+f(n-3)+f(n-7)+f(n-10)


def func(x):
    if 1<=x<3:
        return 1
    elif x<0:
        return 0
    else:
        return func(x-1)+func(x-3)+func(x-7)+func(x-10)

print(func(10))

#22

 

Function namespace

Namespaces are divided into three types: local namespace, global namespace, and built-in namespace 

local namespace: each function has its own namespace, called local space, which records the variables of the function, including function parameters and local Defined variables
def test():
    a =2
    print(a)

test()
print(a)

#2 
#NameError: name 'a' is not defined


Global namespace: Each module has its own namespace, called the global namespace, which records the variables of the module, including functions, classes, and other imported modules.
a=2

def test():
    print(a)

test()
print(a)

#2
#2

 



Built-in namespace: any module can access it, it stores built-in functions and exceptions.
print(),input()...

 

Local and global variables

Local variables: Variables defined inside the function 
Global variables: Variables defined outside the function, if they are immutable types, they cannot be modified inside the function
name='zzq'
list1=[10]
def func():
    name='johnson'
    list1.append(name)
    print("inner",name)
func()
print("outer",name)
print(list1)

#inner johnson
# outer zzq

name ='zzq'
name ='johnson'
def func():
    global name #Global variable
    name='123'
func()
print(name)

# 123

name = 'zzq'
def func1():
    name='ls'
    def func2():
        nonlocal name # When the function local scope cannot find a variable, the interpreter will automatically look for it in the outer function
        name='abc'
    func2()
    print("---------",name)
func1()
print(name)
    • Functions define local scope, while modules define global scope.
      If you want to define the global scope in the function, you need to add the global modifier.
    • Variable name resolution: LEGB principle
      When using unauthenticated variable names in functions, Python searches for 4 scopes [local scope (L) (functions declared internally but not using global variables), followed by the upper layer structure The local scope (E) of def or lambda, followed by the global scope (G) (variables declared in the function using global or variables declared at the module level), and finally the built-in scope (B) (that is, Python's built-in class And functions, etc.)] and stop at the first place where the variable name can be found. If the variable name
      is not found during the entire search process , Python will report an error.
    • Reprinted at https://www.cnblogs.com/summer-cool/p/3884595.html

 

Guess you like

Origin www.cnblogs.com/johnsonbug/p/12610758.html