<Functions of Python (1)>——《Python》

Table of contents

1. Function

2. Grammatical format

2.1 Create function / define function  

​2.2 Call function / use function

3. Function parameters

4. Function return value

5. Variable scope

Postscript: ●Due to the limited level of the author, the article inevitably contains some errors. Readers are welcome to correct me. There are many slang words in this article. I sincerely hope for your advice!

                                                                           ——By Author: Xinxiao·Old Knowing


1. Function

A function in programming is a piece of code that can be reused.
Code example : Find the sum of a series without using functions
#1.求1-100的和
theSum = 0
for i in range(1,101):
    theSum += i
print("1-100的和:",theSum)

#2.求300-400的和
theSum = 0
for i in range(300,401):
    theSum += i
print("300-400的和:",theSum)


#3.求1-1000的和
theSum = 0
for i in range(1,1001):
    theSum += i
print("1-1000的和:",theSum)

 

It can be found that these groups of codes are basically similar , with only a little difference . The repeated code can be extracted and made into a function.
  • In actual development , copying and pasting is not a good strategy . There may be dozens or even hundreds of duplicate codes in actual development .
  • Once this repetitive code needs to be modified , it will have to be modified dozens of times , which is very inconvenient to maintain .
Code example : Find the sum of a sequence , using functions
#定义一个求和函数
def calcSum(begin,end):
    theSum = 0
    for i in range(begin,end+1):
        theSum += i
    print(theSum)

#调用函数
#1.求1-100的和
calcSum(1,100)
#2.求300-400的和
calcSum(300,400)
# 3.求1-1000的和
calcSum(1,1000)
As can be clearly seen, the duplication of code has been eliminated .

2.  Grammatical format

2.1 Create function / define function 

def 函数名(形参列表):
    函数体
    return 返回值

2.2 Call function / use function

函数名(实参列表)           // 不考虑返回值
返回值 = 函数名(实参列表)   // 考虑返回值
  • The function definition does not execute the content of the function body, it must be called before it will be executed . It will be executed several times after calling several times
#定义一个函数
#如果只是定义,而不去调用,则函数体里面的代码就不会执行
def test():
    print("hello")
    print("python")

test()
Function calls will actually execute the code in the function body. 
After a function is defined once, it can be called multiple times.
  • Functions must be "defined before used":
#函数必须先定义, 再使用
test()

def test():
    print("hello")
    print("python")

 

3. Function parameters

When defining a function , you can specify " formal parameters " ( referred to as formal parameters ) in () , and then when calling , the caller passes in " actual parameters " (referred to as actual parameters ) .
In this way , a function can be made to calculate and process different data.
Consider the previous code example :
def calcSum(beg, end):
    sum = 0
    for i in range(beg, end + 1):
        sum += i
    print(sum)
    
sum(1, 100)
sum(300, 400)
sum(1, 1000)
In the above code , beg and end are the formal parameters of the function . 1, 100 / 300, 400 are the actual parameters of the function .
  • When executing sum(1, 100) , it is equivalent to beg = 1, end = 100 , and then the calculation can be performed for 1-100 inside the function .
  • When executing sum(300, 400) , it is equivalent to beg = 300, end = 400 , and then the calculation can be performed for 300-400 inside the function .
The relationship between actual parameters and formal parameters is like signing a contract .
Party A and Party B are equivalent to formal parameters . Cowherd and Weaver Girl are actual parameters .
def 签合同(甲方, 乙方):
    合同内容....
签合同('牛郎', '织女')
签合同('李雷', '韩梅梅')
Note :
  • A function can have one parameter , multiple parameters , or no parameters .
  • There are several formal parameters for a function , so when passing actual parameters, you must also pass several . Make sure that the numbers match .
def test(a, b, c):
    print(a, b, c)
test(10)

 Unlike C++/Java, Python is a dynamically typed programming language , and the formal parameters of the function do not have to specify the parameter type . In other words , a function can support multiple different types of parameters

def test(a):
    print(a)
test(10)
test('hello')
test(True)

 

def add(x,y):
    return x+y


print(add(10, 20))
print(add(1.2, 3.9))
print(add('hello', 'world'))

 

  

 

 4.  Function return value

The parameters of a function can be regarded as the " input " of the function, and the return value of the function can be regarded as the " output " of the function.
  • The " input " and " output " here are input and output in a broader sense , not simply referring to input and output through the console .
  • We can imagine a function as a " factory ". The factory needs to buy raw materials , process them , and produce products .
  • The parameters of the function are the raw materials , and the return value of the function is the produced product .
the following code
def calcSum(beg, end):
    sums = 0
    for i in range(beg, end + 1):
        sums += i
        print(sums)


calcSum(1, 100)

 

can be converted to
def calcSum(beg, end):
    sums = 0
    for i in range(beg, end + 1):
        sums += i
    return sums


result = calcSum(1, 100)
print(result)
The difference between these two codes is that the former prints directly inside the function , while the latter uses the return statement to return the result to the function caller, and the caller is responsible for printing .
We generally prefer the second way of writing .
  • One of our common programming principles in actual development is " separation of logic and user interaction ". The function of the first writing method includes both calculation logic and user interaction ( printing to the console ) . This This way of writing is not very good . If what we need later is to save the calculation results in a file, or send them through the network , or display them in a graphical interface , then the function of the first way of writing will not be able to do it.
  • The second writing method focuses on calculation logic and is not responsible for interacting with users . Then it is easy to match this logic with different user interaction codes to achieve different effects . "Decoupling"
  • There can be multiple return statements in a function
# 判定是否是奇数
def isOdd(num):
    if num % 2 == 0:
        return False
    else:
        return True


result = isOdd(10)
print(result)

  • When the return statement is executed , the function will immediately end and return to the calling location .
# 判定是否是奇数
def isOdd(num):
    if num % 2 == 0:
        return False
    return True


result = isOdd(10)
print(result)
If num is an even number , after entering if , return False will be triggered , and return True will not continue to be executed

 

  • A function can return multiple return values ​​at a time . Use to split multiple return values .
(Note: In C++, if you want to return multiple values, you can pass output parameters (pointers, references)
           In Java, if you want to return multiple values, you need to wrap multiple values ​​into an object and return this object
  )
def getPoint():
    x = 10
    y = 20
    return x, y


a, b = getPoint()
  • If you only want to pay attention to some of the return values, you can use _ to ignore the unwanted return values .

 

def getPoint():
    x = 10
    y = 20
    return x, y


_, b = getPoint()

 

 

5. Variable scope

Observe the following code
def getPoint():
    x = 10
    y = 20
    return x, y


x, y = getPoint()
print(x,y)
In this code , there are x, y inside the function , and x, y outside the function .
But these two sets of x, y are not the same variable , but just happen to have the same name.

 

Variables can only take effect inside the function they are in .
The x and y defined inside the function getPoint() are only valid inside the function . Once out of the scope of the function , these two variables are no longer valid.
def getPoint():
    x = 10
    y = 20
    return x, y


getPoint()
print(x, y)
Variables with the same name are allowed in different scopes
Although the names are the same , they are actually different variables
x = 20


def test():
    x = 10
    print(f'函数内部 x = {x}')


test()
print(f'函数外部 x = {x}')
Notice:

 

  •  Variables inside functions, also known as " local variables "
  • Variables not inside any function , also known as " global variables"
x = 10


def test():
    x = 20
    print(f'函数内部:{x}')


test()
print(f'函数外部:{x}')
If the variable that the function tries to access does not exist locally, it will try to find it in the global scope

 

x = 20


def test():
    print(f'x = {x}')


test()
If you want to modify the value of the global variable inside the function , you need to use the global keyword declaration

 

x = 20


def test():
    global x
    x = 10
    print(f'函数内部 x = {x}')


test()
print(f'函数外部 x = {x}')
If there is no global here, x = 10 inside the function will be regarded as creating a local variable x, which is the same as the global

The variable x is irrelevant .

Statement blocks such as if / while / for will not affect the variable scope
In other words , variables defined in if / while / for can also be used normally outside the statement .
for i in range(1, 10):
    print(f'函数内部 i = {i}')
print(f'函数外部 i = {i}')

Keywords such as if, else, while, for also introduce "code blocks", but these code blocks will not affect the scope of variables! Variables defined inside the above statement code block can be accessed outside!

 

 

for i in range(1, 9):
    print(i)


print('-------')
print(i)

 

Postscript:
●Due to the limited level of the author, there are inevitable errors in the article. Readers are welcome to correct the article, and the article is full of slang, and I sincerely hope to give advice!

                                                                           ——By Author: Xinxiao·Old Knowing

 

Guess you like

Origin blog.csdn.net/m0_57859086/article/details/128570826