python6 - Functions (parameters, anonymous functions, recursive functions)

Keywords: Python Pycharm crawler

1. Overview of Functions

  • If you need a block of code several times when developing a program, in order to improve writing efficiency and code reuse, you organize code blocks with independent functions into a small module, which is a function.

We've been exposed to a number of functions, such as input(), print(), range(), len(), and so on, which are built-in functions of Python and can be used directly.Functions in programming languages can be summarized in the following figure:

  • From the point of view of implementing a function, it needs to think about at least three things:
    Functions require several key data that needs to be dynamically changed, which should be defined as the parameters of the function.
    A function needs to pass out several important pieces of data (that is, the data the caller wants), which should be defined as return values.
    Internal implementation of functions

2. Creation and Call of Functions

def get_max(num1,num2):
    result = num1 if num1 > num2 else num2
    return result
max_num = get_max(30,80)
print(max_num)

Defining a function, that is, creating a function, can be understood as creating a tool with some purpose.Defining a function requires a def keyword

Define an empty function that does nothing, using pass statements;Pass can be used as a placeholder. Before you know how to write the code for a function, you can put a pass first so that the code can run.

To call a function is to execute it.If you think of a created function as a tool with some purpose, calling a function is equivalent to using the tool.
Basic syntax for function calls: function name ([parameter value])

  • The so-called "return value" is the result that a function in a program finishes one thing and gives to the caller at the end.No return value, default return None
  • Theoretically, you can program without functions. If you have written a program before, you won't write a function. Of course, using python's built-in function will be an exception.The main reasons for using functions now are:
    Reduce the difficulty of programming (the idea of dividing and conquering)
    Code reuse.Avoid duplicate work and provide efficiency.

3. Scope of Variables

1. Local variables

  • A local variable is a variable defined within a function
  • Different functions can define local variables with the same name, but each has no effect

2. Global variables

  • If a variable can be used in either one function or another, it is a global variable.



The essence of globals is to declare that you can modify the direction of global variables, that is, variables can point to new data.

1). Global variables of immutable type: The data pointed to cannot be modified, and global variables cannot be modified without using globals.

2). Global variables of variable type: Pointing data can be modified, and global variables can be modified without using globals.

4. Transfer of Function Parameters

1. Formal and practical parameters

  • Parameters in parentheses when defined and used to receive parameters are called "formal parameters"
  • Parameters in parentheses when called, used to pass to a function, are called arguments

Where, (num1,num2) is a formal parameter, (100,211) is an actual parameter

def get_max(num1,num2):
    return num1 if num1 > num2 else num2
result = get_max(100,211)
print((result))

2. Parameter Check

When a function is called, if the number of parameters is not correct, the Python interpreter automatically checks it out and throws a TypeError.

  • If the parameter type is not correct, the Python interpreter will not be able to check for us.
  • Data type checking can be implemented with the built-in function isinstance
def get_max(num1:int,num2:int)->int:
    return num1 if num1 > num2 else num2
result = get_max('jia',211)
print((result))

def get_max(num1:int,num2:int)->int:
    if isinstance(num1,int) and isinstance(num2,int):
        return num1 if num1 > num2 else num2
    else:
        return 0
result = get_max('jia',211)
print((result))

Fifth, Four Parameter Types

1. Required parameters

  • Parameters that must be passed

The parameter requires two parameters, but the parameter cannot be one, it must be two, otherwise an error will be made!

2. Default parameters

  • Default parameters reduce the difficulty of calling functions.
  • Default functions are error prone: variable parameters cannot be used as default parameters.
def pow(x,y=2):
    return x ** y
result = pow(2)
print(result)
result = pow(2,3)
print(result)

3. Variable parameters

  • A variable parameter means that the number of parameters passed in is variable and can be one, two, or any number, or zero. *args - actually saved in is a tuple
def my_sum(*args):
    return sum(args)
result = my_sum(1,2,3,4,5,6)
print(result)

4. Keyword parameters

def enroll(name,age=18,*city,**kwargs):
    print(f"""
        haha
    1.name:{name}
    2.age:{age}
    3.city:{city}
    4.others:{kwargs}
    """)
enroll('user1',sport='basketball',english='cet4',gender='man')

6. Anonymous functions

get_max = lambda num1,num2:num1 if num1>num2 else num2
print(get_max(10,244))

pow = lambda x,y=2: x ** y
print(pow(2))

7. Recursive Functions

  • Known: Functions can call functions.Conclusion: A function calls itself internally, which is a recursive function.
def f(n):
    if n == 1:
        return 1
    return n * f(n-1)
print(f(4))


Fibonacci series:

def fib(n):
    if n == 1 or n == 2:
        return 1
    return fib(n-1) + fib(n-2)
print(fib(6))

Practice


Disorganization ideas:

nums = [0,7,0,2]
nums.sort(key=lambda num:1 if num==0 else 0)
print(nums)


Deformation: even numbers on the left, odd numbers on the right

nums = [0,7,0,2]
nums.sort(key=lambda num:0 if num%2==0 else 1)
print(nums)

Posted by kenchucky on Tue, 07 Sep 2021 17:13:49 -0700