[Python] basic grammar-6, function design

1.6 Function design

Function concept

Functions can be used to define reusable code, organize and simplify code

# 计算1~10的和
sum = 0
for i in range(1, 11):
    sum += i
print(sum)
# 计算2~22的和
sum = 0
for i in range(2, 23):
    sum += i
print(sum)
# 计算9~101的和
sum = 0
for i in range(9, 102):
    sum += i
print(sum)
# 封装
def getSum(a, b):
    result = 0
    for i in range(a, b + 1):
        result += i
    return result
sum = getSum(1,10)
print(sum)
sum = getSum(2,22)
print(sum)
sum = getSum(9,101)
print(sum)

A function is a set of statements assembled to implement an operation

What are the benefits of functions:

  • The use of functions can reuse code, save repetitive code writing, and improve code reuse

  • Function can encapsulate internal implementation, protect internal data, and achieve transparency to users

  • Functions make the program modular, with clear division of labor, which is conducive to reading, debugging and modification.

Function definition

The main components of the function are: function name, parameters, function body and return value

def 函数名称(参数):
    函数体
    return 返回值

Parameters are called formal parameters or formal parameters . When the function is called from outside, some data will be passed, and these data will be received by the formal parameters. The data passed in is called actual parameter or actual parameter . The parameter is optional.

num1 = 30;
num2 = 40;
sum = getSum(num1,num2)
print(sum)

Some functions have return values , and some functions do not. Is there no return without a return value? If there is no return value, return is hidden.

def getSumPrint(a,b):
    result = 0
    for i in range(a, b + 1):
        result += i
    print(result)
    # return
getSumPrint(10,20)

The function body contains a set of statements that define what the function does.

Return only means the end of the function operation. Once the function execution process encounters the return statement, all the code after the function is ignored, and the function body is directly jumped out, and the function ends immediately, even in a loop. And if the function has no return value, it will return None by default; if there is a return value, just write it after return, end the function and return the result to the caller.

def func01(a):
    if a == 10:
        print("哈哈")
        return
    print("嘻嘻")
    return
func01(11)
res = func01(10)
print(type(res))
def func02(a):
    for i in range(1,11):
        if i == a:
            print(i)
            # break 跳出循环 接着向下运行
            return  # 直接结束函数
        print(i)
    print("啦啦")
    return
func02(11)
func02(4)

What can be returned by return?

  • Return nothing:return

  • Any data type:return 'hello'

  • An expression:return 1 + 2

  • A judgment statement:return 3 > 2

  • A variable:return a

  • A function call:return func()

  • Multiple return values, separated by commas:return a,1+2,'hello'

  • Even return to yourself:return self

Functions can return almost all Python data objects.

Passing of parameters

Functions usually have parameters, which are used to pass actual external data into the function for processing. However, when processing parameters of different data types, the following two things will happen:

  • When a Python function passes parameters, it passes the memory address of the actual object

  • Python data types are mainly divided into mutable objects and immutable objects

def func(a): # 局部变量
    print("函数内部没有修改前",id(a)) # 520
    a = 2
    print("函数内部修改后",id(a)) # 536
    print("函数内部修改后a=",a) # 2
    return
a = 1   # 全局变量
print("调用函数之前",id(a))   # 520
func(a)
print("调用函数之后",id(a))   # 520
print(a)

def test(lst) :
    lst.append(4)
    print(id(lst))
    print(lst)
lst = [1,2,3] # 列表
print(id(lst))
test(lst)
print(id(lst))
print(lst)

Regarding the transfer of parameters, since Python is a dynamic language, there is no data type distinction for variables, so the function will not detect the data type of the actual parameter, but it will detect the number; the detection of the data type will only be detected when the function is running. come out.

def add(a, b):
    return a + b
add(1, 2)
add(1, 2, 3)
Traceback (most recent call last):
  File "C:/Users/HENG/Desktop/PythonCode/Day04/FunctionTest05.py", line 5, in <module>
    add(1, 2, 3)
TypeError: add() takes 2 positional arguments but 3 were given
    
add(1, "hello")
Traceback (most recent call last):
  File "C:/Users/HENG/Desktop/PythonCode/Day04/FunctionTest05.py", line 6, in <module>
    add(1, "hello")
  File "C:/Users/HENG/Desktop/PythonCode/Day04/FunctionTest05.py", line 2, in add
    return a + b
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Function operation mechanism

A stack is a first-in-last-out container.

Functions are run based on the stack. Every time a function is called, the system automatically creates a memory space for the function, also called a stack frame, stores its parameters, variables, and execution statements, and then pushes the stack frame into the stack to start running. When a function calls another new function, then the system creates a new stack frame, pushes the stack frame to the stack and starts to run, then the first function is suspended until all functions on it are executed, the first The function continues to execute.

def multi(a, b, c):
    return a ** 2, b ** 2, c ** 2
def add(a, b, c):
    return a + b + c
def out(s):
    print(s)
def test(a, b):
    num1, num2, num3 = multi(a, b, a + b)
    out('hello')
    return add(num1, num2, num3)
num = test(2, 3)
print(num)

Variable scope

The variables defined inside the function are called local variables . Local variables can only be accessed inside the function. The function where the scope of the local variable is located is pushed into the stack and executed until the function ends and pops out of the stack.

It is also possible to define global variables , which are defined outside of all functions and can be accessed by all functions.

Example 1:

globalVar = 1
num1 = 3
num2 = 10
def f1():
    localVar = 2    # 局部变量 在该函数内创建
    print(globalVar)    # 全局变量
    print(localVar)     # 局部变量
    print(num1 + 3)      # num1 全局变量
    num2 = 20       # 局部变量 在该函数内创建
    print(num2)
    # 如果直接将全局变量,参与运算,直接打印 调用的就是全局变量
    # 如果是对全局变量进行修改,则为创建一个同名的局部变量
f1()
print(globalVar)
print(num2)
# NameError: name 'localVar' is not defined
# print(localVar)

Example 2:

x = 1
def f2():
    global x    # 在函数内部将x标记为全局变量,如果存在则复用,不存在则创建全局变量
    x = 2
    print(x)
f2()
print(x)
==========================================
def f2():
    global x    # 在函数内部将x标记为全局变量,如果存在则复用,不存在则创建全局变量
    x = 2
    print(x)
f2()
print(x)

Example 3:

x = int(input("Enter a number:"))
if x > 0:
    y = 4   # 全局变量 只有在x>0的条件下创建
print(y)
Enter a number:-10
Traceback (most recent call last):
  File "C:/Users/HENG/Desktop/PythonCode/Day04/FunctionTest05.py", line 52, in <module>
    print(y)
NameError: name 'y' is not defined

Example 4:

sum = 0
for i in range(5): # i 全局变量
    sum += i
print(i) # --> 4

 

Guess you like

Origin blog.csdn.net/trichloromethane/article/details/108267386