[Burst Liver Update] Python Basic Tutorial: Chapter 5_Python Functions

Original: Public account data talk

[Burst Liver Update] Python Basic Tutorial: Chapter 5_Python Functions

Function introduction

learning target:

  • Quickly experience the use of functions

  • Understand what functions do.

Function: It is an organized, reusable code segment used to implement a specific function. If this sentence is not easy to understand, we can look at the following example:

 
 
 
 

name = "itheima"
length = len(name)
print(length)

#The result is: 7

Why can you use len() to count the length at any time? Because, len() is a built-in function of Python:

• is written in advance

• Can be reused

• A code segment that implements the specific function of counting lengths

We have used: input(), print(), str(), int(), etc. are all built-in functions of Python.

Next, let's make a practical small case, let us experience the use of functions, then the requirements of the case are actually very simple, we don't use the built-in function len provided by Python, we have to develop the function by ourselves, to complete Calculation of string length.  

 
 
 
 

"""
Demo: quickly experience the development and application of functions
"""
#Requirements, count the length of the string, do not use the built-in function len()
str1 = "itheima"
str2 = "itcast"
str3 = "python"

#Define a count The variable
count = 0
for i in str1:
count += 1
print(f "The length of the string {str1} is: {count}")

count = 0
for i in str2:
count += 1
print(f "The string The length of {str2} is: {count}")

count = 0
for i in str3:
count += 1
print(f"The length of the string {str3} is: {count}")

Did we find the code a bit repetitive? How are they different? The only difference is the string being counted, otherwise the codes are identical. This exact same code would feel like a waste, right? This way of writing is very inefficient. So how to improve efficiency? We can use functions to optimize this process, as demonstrated below.  

Ok, now I'll simply define a function. We named it "mylen", the function of this function is to calculate the length of the data. Now that I write this code, some students may not understand it, but it doesn't matter, we just need to see the result.  

 
 
 
 

# Functions can be used to optimize this process
def my_len(data):
count =0
for i in data:
count += 1
print(f"The length of the string {data} is {count}")
my_len(str1)
my_len( str2)
my_len(str3)

Ok, so we have simply defined a function. After we define the function, we can use it. The method of use is also very simple, just call the function "mylen", and put the string whose length needs to be calculated in the function.

Run, you can see the output is

 
 
 
 

The length of the string itheima is 7
The length of the string itcast is 6
The length of the string python is 6

The result is the same as the first run, through this code, you can compare whether there is any difference between them.

The difference is that our function seems to encapsulate this repetitive work. In this repeated code, the only variable is the string being counted. When using it, we only need to pass in the string whose length needs to be counted as a parameter. It can dynamically calculate the length based on the content you provide.

Therefore, through this simple code, students can find that using functions can avoid repeated code writing. Also, the function we wrote called "mylen" can be reused. Let's look again at our simple definition of a function:

The first is organized, the second is reusable, and the third is function-specific.

Now look at the function we wrote, first of all, does it satisfy the organized? That means I wrote its functional logic ahead of time.

Second, is it reusable? No problem, we use "mylen" a lot, right?

The third point is for specific functions. You look at the "mylen" function we wrote, what does it do? It calculates the length of the string. Therefore, the function we wrote fully meets these three characteristics, which is a typical function.

function definition

In one section, we have a basic experience with functions, so now let's learn the definition of functions. The goal of this section is also very clear. In this section, we will complete the basic definition syntax of functions.

Function definition:

First, let's take a look at the definition syntax of the function, which is relatively simple. We can use the def keyword to indicate that we want to write a function. Then we write the function name after the space, and we can write the incoming parameters in parentheses. Finally pass a colon as the end of the current line. This colon is also what we often see, for example, it will appear in for loops, while loops, and if judgments. After we write the colon, the following lines will be indented with spaces.

Next, we can wrap the line below to write the function body. The function body refers to what the function does. After completing the body of the function, we can finally return a value via a return.

 
 
 
 

def function name (incoming parameters):
function body
return return value

Therefore, the composition of a function is the keyword def, function name, incoming parameters, function body and return value.  

In our current basic definition syntax, we don't discuss the incoming parameters and return values ​​for the time being. Both of these can be omitted, and we will discuss them in detail in later chapters. So so far, our basic function definition only needs to write the def keyword, give the function name, and write the function body. So we only need to have these 3 elements.

Function call:

 
 
 
 

function name (parameter)

Notice:

① The parameters can be omitted if they are not needed (explained in the following chapters)

② If the return value is not required, it can be omitted (explained in subsequent chapters)

③The function must be defined first and then used So far, we only need to write the def keyword, give the function name, and write the function body for a basic function definition, so we only need to have these 3 elements. OK, let's give an example:

 
 
 
 

# Define a function to output relevant information
def say_hi():
print("Hi, I am a dark horse programmer, learn Python to be a dark horse")

After defining a function, in order for it to work, a call must be made. It's as if you have a tool, and if you want to use it, you have to power it up. When we call a function, it is equivalent to powering up the tool to make it actually work. Therefore, we need to call the function in order to let the defined function perform the task.

Next, let's take a look at how the syntax of the second function should be written. This process is very simple, just write the function name, and then write the parameters in parentheses. However, it should be noted that when we omit parameters when defining a function, we can also not pass parameters when calling, just write the function name and leave blank in the parentheses.

 
 
 
 

# Call the function to let the defined function start working
say_hi()

In this way, the result is output:

 
 
 
 

Hi, I am a dark horse programmer, learning Python to come to dark horse

Precautions:

  • The parameter is not required and can be omitted

  • The return value is not required and can be omitted

function parameters

In the previous section, we completed the basic definition of the function, and we said that the incoming parameters can be used in the definition of the function, but we did not analyze it, so in this section we will explain about the parameters of the function usage of.

learning target:

  • Master how to use incoming parameters

The incoming parameters of the function

The function of passing in parameters is: when the function is calculating, it accepts the data provided by the outside (when calling), so how to use it specifically, let's first look at a case, there is the following code, and the addition of two numbers is completed The function:

 
 
 
 

def add():
result = 1 + 2
print(f"1+2 result is: {result}")
add()

The function is very limited and can only calculate 1+2. Is it possible to achieve: each time the function is used, to calculate the 2 numbers specified by the user, instead of 1 + 2 every time? Yes, it can be realized by using the parameter passing function of the function.

The incoming parameters of the function - the parameter definition

First, based on the definition syntax of the function, you can see whether there is a syntax for passing in parameters in the parentheses. So when we define parameters, we can write the parameter definitions here.

 
 
 
 

def function name (incoming parameters):
function body
return return value

For example, in the function of adding two numbers just now, we can write x and y in the brackets, which means that I receive the input of two parameters, so how do I write it when I calculate, we no longer write 1 +2, we directly write x and y to add, and then we can get the specific result and output it. Then when we write in this syntax, every time we call the function, we can manually Specify the number of x and the number of y, then each calculation will be added to whoever is specified by our user. Isn't this perfect?

You can have the following function definitions:

 
 
 
 

def add(x,y):
result =x + y
print(f"{x}+{y}The result is: {result}")

It is realized that x + y is calculated each time, instead of a fixed value of 1 + 2, which can be specified when calling the function.

 
 
 
 

# Call the function and pass in the calculated 2 numbers
add(5, 6)

The result is 11

The incoming parameters of the function - syntax analysis

Grammar analysis:

 
 
 
 

#Define function
def add(x,y):
result= x + y
print(f"{x}+{y}The result is: {result}")
#Call function
add(5,6)

  • In the function definition, the x and y provided are called: formal parameters (formal parameters), indicating that the function declaration will use 2 parameters

  • Parameters are separated by commas

  • In the function call, the 5 and 6 provided are called: actual parameters (actual parameters), which represent the parameter values ​​actually used when the function is executed

  • When passing in, pass in the data in order, separated by commas

So after parsing, let's take a look at the functions we are currently defining. It is a function of two parameters, so our function can only accept two incoming parameters? Obviously not. Through the previous study, we know that functions can use no parameters. Then through the code just now, we found that functions can also use parameters. We used 2, but actually the function can take any n arguments. You can give 1, you can give 2, you can give 3, or you can give 10. You can give as many as you want.

The number of incoming parameters is unlimited.

  • You can use no parameters

  • It is also possible to use only any N arguments

You can change the code just now to 3 parameters:

 
 
 
 

# Define the function of adding 3 numbers, and receive the calculated 2 numbers through parameters
def add(x, y, z):
result = x + y + z
print(f"{x} + {y} + {z} The calculation result is: {result}")

# Call the function and pass in the calculated 3 numbers
add(5, 6, 7)

Is it also calculated, so the number of our incoming parameters is unlimited.

function return value

In this section of the function return value, we mainly divide it into two parts to explain. First, let us learn the first part, the definition syntax of the function return value. learning target,

  • Be able to grasp the role of the return value

  • Return value definition syntax

what is return value

Return value in life:

To give a small example in life, for example, I asked Xiao Ming to buy three bottles of Coke. You can think of Xiao Ming as a function, and asking him to buy three bottles of Coke is equivalent to passing parameters to the function. Once the parameters are passed, Xiaoming's function will start to work, and he will respond: "I'm going to buy a Coke". After he buys the Coke, he will give the Coke to me. This Coke is equivalent to the return value of the function.

Therefore, the example in life is very simple, that is, I ask you to do one thing, and you will give me a result after you finish it. In programs, we also need to focus on the outcome of things!

For the return value in the code program:

Let's take a look at the feedback in the code. Defines a simple function to add two numbers. The function of this function is very simple, add a and b, and store the result in the variable result. Then we used a keyword called return in the code. Its function is to return the value after return.

What does it mean to go back out? Let's look at the following code. When we call the function add, you will find that its result is received by a variable called result. When we use print to output this variable, the result is 3. Doesn't this represent the result of adding 1 and 2? This return statement has returned its return value and is received by result.

 
 
 
 

def add(a,b):
result = a +b
return result
result = add(1,2)
print(result)

Defines the function function of adding two numbers. After the function is completed, the addition result will be returned to the function caller, and the variable r receives the execution result of the function.

In summary:

The so-called "return value" is the final result to the caller after the function in the program completes its work.

After the info function executes the return value, all subsequent codes will not be executed. Therefore, as long as the function body encounters the return keyword, it will end immediately. If you add a sentence after retern result: print("I'm done") will not execute at all. Therefore, we need to pay attention to this detail.

Syntax for return value:

The syntax format is as follows:

 
 
 
 

def function (parameter...):
function body
return return value
variable = function (parameter)

As above, the variable can receive the return value of the function to practice it: define a function, complete the function of adding two numbers, and return the result. The syntax is: through the return keyword, the data can be returned to the caller.

None type

Thinking: If the function does not use the return statement to return data, does the function have a return value?

Actually: yes.

There is a special literal in Python: None, whose type is: a function with no return value, which actually returns: the literal value of None

None means: empty, meaningless

If the function returns None, it means that the function does not return any meaningful content.

That is to say, it returned empty.

That is to say, whether you write the return statement or not, our function essentially has a return value, and if you don't write it, it returns none.

So when we write a function to call it, such as the following code, this function does not declare our return statement, but essentially you can use a variable to receive its return value, and print its content and print Its type, you will find that the result is None type is our None type. Or as we said, the None can also be returned, and you can manually return None, which is also possible.

Demo:

 
 
 
 

def say_hello():
print("Hello...")

#Use a variable to receive the return value of the say_he1lo function
result = say_hello()
# print the return value
print(result) # result None
# print the return value type
print(type(result) ) # result <class'NoneType'>

None can actively use return to return, the effect is equivalent to not writing a return statement:

 
 
 
 

def say_hello():
print("Hello...")
return None

#Use a variable to receive the return value of the say_hello function
result = say_hello() # print the return value
print(result) #result None

Application scenarios of None type

None, as a special literal, is used to represent: empty, meaningless, and it has many application scenarios.

  • Used on functions with no return value

  • Used in if judgment

  • In the if judgment, None is equivalent to False

  • Generally used to actively return None in the function, and cooperate with the if judgment to do related processing

  • Used to declare variables with no content

  • Define variables, but temporarily do not need variables to have specific values, you can use None instead

 
 
 
 

#Do not assign specific values ​​to variables
name = None

We now have a simple function, its function is very simple, check your age, and then determine whether your age is greater than 18 years old, adult is enough. If the age you pass in is greater than 18, we return a valuable value called SUCCESS, which means success. But if your age is not met to be greater than 18, we return None. For this kind of function, we can call it later, for example, after the check_age function calls it, if I pass a 16-year-old, then it must return None, and then get a result. Then we can judge whether the result is None, we can write if result == None, but this is a bit long-winded. We can directly write if not result, so that we can judge whether the resource is a None value.  

 
 
 
 

def check_age(age):
if age >18:
return "SUCCESS"
return None

result = check_age(5)
if not result:
print("Underage, not allowed to enter")

OK, I can briefly say something after you come in. We do not allow minors to enter this Internet cafe. Therefore, we need to use a simple function to return a value, and then use the if statement to judge. Since our return value is None, which means False, we can judge the return value through the if statement, and then perform corresponding operations.  

function documentation

learning target

  • Master the explanation of functions through comments

Function is a pure code language. To understand its meaning, you need to read and understand the code line by line, which is relatively inefficient.

We can add documentation to the function to help understand the function of the function.

The syntax is as follows:

 
 
 
 

def func(x,y):
"""
Function description
: param x: description of formal parameter x
: param y: description of formal parameter y
: return: description of return value
"""
function body
return return value

In the above code, we added a multi-line comment between the function definition and the function body, which is the documentation of the function. Although essentially you are free to write multi-line comments, if you want to be more standardized, it is more useful for us to follow some grammatical formats.  

In this multi-line comment, we can describe the function as a whole, use the colon param to describe the parameter x, use the colon param to describe the formal parameter y, and use the colon return to describe the return value. Through this format, we can not only explain the function as a whole, but also explain its parameters and return values ​​accordingly.

Note: the content should be written before the function body

Let's walk through the code in practice:

 
 
 
 

"""
Demonstrates the documentation of functions
"""

# Define functions and perform documentation
def add(x, y):
"""
The add function can receive 2 parameters and perform the function of adding 2 numbers
: param x: Form The parameter x represents one of the numbers to be added
: param y: The formal parameter y represents another number to be added
: return: The return value is the result of adding 2 numbers
"""
result = x + y
print(f"2 number phase The result of the addition is: {result}")
return result

add(5, 6)

View function documentation in PyCharm

When writing code in PyCharm, you can view the documentation of the calling function by hovering the mouse, which is very useful. When we write functions in the future, as long as you write a function, we recommend that you fill in the documentation for it, so that it is a more standardized function definition.  

nested function calls

learning target

  • Master nested calls of functions

  • Understand the execution flow of nested calls

What is function nesting

The so-called function nested call refers to a function that calls another function. When you have this behavior, we call it a function nested call. For example, in the code below, we define two functions, namely fun_b and fun_a. In fun_a, it calls fun_b, and then we call the function fun_a to let it execute. When I execute the fun_a function, you can see that its execution results output 1, 2, and 3. So, in fun_a, we first output 1, then call b, output 2, and finally output 3. This is a form of nested calls to functions.  

 
 
 
 

def func_b():
print("---2---")
def func_a():
print("---1---")
func_b()
print("---3---")
# 调用函数func a
func_a()

Execution effect:

 
 
 
 

---1---
---2---
---3---

Then the process of nested transfer is very simple, we also briefly analyzed it. Let's move on to the next section.

variable scope

learning target

  • Know what is a local variable

  • Know what is a global variable

local variable

The variable scope refers to the scope of the variable (where the variable is available and where it is not available). It is mainly divided into two categories: local variables and global variables. The so-called local variables are variables defined inside the function body, that is, only inside the function body take effect

 
 
 
 

def testA():
num = 100
print(num)

testA() # 100
print(num) # 报错:name'num'is not defined
#

Variable a is a variable defined inside the testA function, and if it is accessed outside the function, an error will be reported immediately, and it will prompt you that name number is not defined. He said that the number variable has not been defined, so this is a local variable.

The role of local variables: inside the function body, temporarily save data, that is, when the function call is completed, the local variables are destroyed

global variable

The so-called global variable refers to the variable that can take effect inside and outside the function body.

Thinking: What should I do if there is a piece of data that is used in both function A and function B? Answer: Store this data in a global variable  

So, how to use global variables? In fact, it is very simple, just define the variable outside the function. As long as it is not inside the function, the variable can be used normally in the function and outside the function.

As shown in the code below, both test_a and test_b can call num.

 
 
 
 

#Define global variable a
num = 200

def test_a():
print(f"test_a: {num}")

def test_b():
print(f"test_b: {num}")

test_a()
test_b()
print(num)

global keyword

Well, after understanding local variables and global variables, let's look at the next content, called the global keyword. Now we have a need to modify the value of the global variable inside the function, for example, change it from 100 to 200. Will this modify operation succeed? Let's try it out. In the following code, write a function to modify the global variable, for example, change the number to 500 in test_b. The execution sequence is to call test a first, then call test b, and finally output num. When outputting the num at the end, the num has been changed to 500. Let's see if the num of the last output is 200 or 500. OK, now let's run it.  

 
 
 
 


# modify the global variable num = 200 in the function

def test_a():
print(f"test_a: {num}")

def test_b():
num = 500 # local variable
print(f"test_b: {num}")

test_a( )
test_b()
print(num)

The result of the operation is:

 
 
 
 

test_a: 200
test_b: 500
200

You will find that the value of test_a is 200, no problem. What about test_b? The number it outputs has been successfully modified to 500? This is okay, but the number outside the function is still 200, which means that our modification in this step does not seem to take effect on it. Why is this? Because that number we defined inside the function is actually a local variable. That is to say, we define a variable called num inside the function and set its value to 500. This num is normally used inside our function, but it has nothing to do with the num outside the function. It is equivalent to us defining a new variable, which is only used inside the function. So, although you can get 500 internally, but externally, whether the number is 200 or 200, there is no connection between them.

How to modify the program? Just add a global keyword:

☆ Use the global keyword to declare variables as global variables inside the function, as shown below

 
 
 
 

# global keyword, declare the variable as a global variable in the function
num = 200

def test_a():
print(f"test_a: {num}")

def test_b():
global num # set the internally defined variable as the global variable
num = 500
print(f"test_b: {num}")

test_a()
test_b()
print(num)

Output result:

 
 
 
 

test_a: 200
test_b: 500
500

Finally, the num becomes 500 output, which is the role of the global keyword, which allows us to define variables in the function as global variables.  

Comprehensive case

Let’s look at a case: Dark Horse ATM, to achieve the following effects: Main menu effect

  • Query balance effect

Deposit and withdrawal effect

Ideas:

  • Define a global variable: money, used to record the bank card balance (default 5000000)

  • Define a global variable: name, used to record the customer name (entered when starting the program)

  • Define a function like this:

  • Query balance function

  • deposit function

  • withdrawal function

  • main menu function

Require:

  • After the program starts, it asks for the customer's name

  • You will return to the main menu after checking the balance, depositing, and withdrawing money

  • After depositing and withdrawing, the current balance should be displayed

  • If the customer chooses to exit or enters an error, the program will exit, otherwise it will keep running

Reference Code:

 
 
 
 

"""
Demo function comprehensive case development
"""

#Define global variable money name
money = 5000000
name = None
#Require customers to enter name
name = input("Please enter your name:")
#Define query function
def query(show_header) :
if show_header:
print("-------------Check balance------------")
print(f"{name}, hello, your balance Surplus: {money} yuan")


#Define the deposit function
def saving(num):
global money # Money is defined as a global variable inside the function
money += num
print("-------------deposit ------------")
print(f"Hello {name}, your deposit {num} was successful.")

# Call the query function to query the balance
query(False)

# Define the withdrawal function
def get_money(num):
global money
money -= num
print("-------------Withdrawal------------")
print(f"Hello {name}, you have successfully withdrawn {num} yuan.")

# Call the query function to query the balance
query(False)
# Define the main menu function
def main():
print("------ -------Main Menu------------")
print(f"{name}, hello, welcome to Heima Bank ATM. Please choose operation:")
print(" Query balance\t[input 1]")
print("deposit\t\t[input 2]")
print("withdrawal\t\t[input 3]") # Align output by \t tab
print(" Exit\t\t[Input 4]")
return input("Please enter your choice:")

# Set an infinite loop to ensure that the program does not exit
while True:
keyboard_input = main()
if keyboard_input == "1":
query( True)
continue # Continue the next cycle through continue, and return to the main menu as soon as you enter
elif keyboard_input == "2":
num = int(input("How much do you want to save? Please enter:"))
saving(num)
continue
elif keyboard_input == "3":
num = int(input("How much do you want to withdraw? Please enter:"))
get_money(num)
continue
else:
print("The program has exited")
break # Exit the loop through break

The code is long, you can practice writing it yourself first, and disassemble the code in the reference.

Guess you like

Origin blog.csdn.net/Blue92120/article/details/130607219