Python basics: (6) function --- basic knowledge

1. Define the function

  • Learning to use functions can simplify complex tasks. The "essence of functions" is to encapsulate a part of code into function calls. You can call functions without a limit on the number of times.
  • The previous article more or less involved the knowledge of some functions, some of which are packaged by the system, we only need to call them, and we can also write our own functions.
  • Use the keyword def xxx(): Tell the python interpreter whether this is a function or :ends with .
  • () The inside of the brackets can indicate what information the function needs, of course, you can also write nothing, but you can’t omit the brackets!
  • A function is composed of a function name and a function body, and all indentation after the function name indicates the function body.
  • When writing a function, you also need to explain the function of the function, that is, comments, using """""" (comments for documentation strings).

eg:

def welcome():
    """"打印欢迎来到python世界"""
    print(" 欢迎来到python世界!")
welcome()

insert image description here

2. Passing actual parameters

Before proceeding to this section, some knowledge needs to be supplemented, or the previous function welcome, with a slight change.

2.1 Supplement: function transfer information

def welcome(name):
    """"打印欢迎来到python世界"""
    print(f"{
      
      name}欢迎来到python世界!")
welcome('mayahei')
#用户调用welcome函数时,把输入的mayahei传递给name,也就是把name替换成mayahei。

insert image description here

2.2 Supplement: actual parameters and formal parameters

Still take the welcome function as an example

def welcome(name):
    """"打印欢迎来到python世界"""
    print(f"{
      
      name}欢迎来到python世界!")
welcome('mayahei')

In this function, 实参为:mayehei
                         形参为:name

  • A function call is value passing, passing the value of the actual parameter to the formal parameter, and then calling the value of the actual parameter in the function.
  • Formal parameters and actual parameters may not be clear when you first come into contact with them, but you will gradually understand them as you become more skilled in writing code. Sometimes you may see someone refer to variables in function definitions as actual parameters, and call variables in function calls Don't be surprised if the variables of the .

2.3 passing actual parameters

A user-defined function may contain multiple formal parameters, that is, when you make a function call, it should also contain multiple actual parameters. There are many ways to pass actual parameters, that is to say, you can use different function calls to output the same result. Here, I will explain some methods of passing actual parameters for you one by one.

2.3.1 Positional arguments

Note : The positional actual parameter, as the name implies, means that the transfer of the actual parameter and the formal parameter is one-to-one correspondence when the function is called. As mentioned above, assign multiple variables x, y, x = 1, 2, 3; x = 1; y = 2; z = 3;

This is explained with examples in the python reference book.

The one-to-one correspondence between actual parameters and formal parameters is correct:

def describ_pet(animal_type,pet_name):
    """"显示宠物的信息"""
    print(f"\n我有一只{
      
      animal_type}.")
    print(f"我的{
      
      animal_type}的名字是{
      
      pet_name}")
describ_pet('猫','花花')

insert image description here
Correspondence error between actual parameter and formal parameter

def describ_pet(animal_type,pet_name):
    """"显示宠物的信息"""
    print(f"\n我有一只{
      
      animal_type}.")
    print(f"我的{
      
      animal_type}的名字是{
      
      pet_name}")
describ_pet('花花','猫')

insert image description here

ps: Although there is no grammatical error, there is an error in the logic. This kind of error is generally not easy to check, so we must pay attention to the correspondence between the formal parameters and the actual parameters. So there is no way to avoid it, then see the next part Keyword arguments.

2.3.2 Keyword arguments

The essence of the keyword actual parameter is to assign the value of the actual parameter to the corresponding formal parameter when the function is called.

def describ_pet(animal_type,pet_name):
    """"显示宠物的信息"""
    print(f"\n我有一只{
      
      animal_type}.")
    print(f"我的{
      
      animal_type}的名字是{
      
      pet_name}")
describ_pet(pet_name='花花',animal_type='猫')

insert image description here

2.3.3 Assign default values ​​to formal parameters

Sometimes, for example, your pets are all cats, but you don’t want to enter cats every time, then you can set cats as the default value, because the formal parameters and actual parameters are one-to-one correspondence, so the default value must be placed at the end. See the example below.

It is essentially to give a certain amount to the formal parameter when customizing the function.

def describ_pet(pet_name,animal_type='猫'):
    """"显示宠物的信息"""
    print(f"\n我有一只{
      
      animal_type}.")
    print(f"我的{
      
      animal_type}的名字是{
      
      pet_name}")
describ_pet('花花')
describ_pet('美媚')

insert image description here

2.3.4 Different function calls output the same result
def describ_pet(pet_name,animal_type='猫'):
    """"显示宠物的信息"""
    print(f"\n我有一只{
      
      animal_type}.")
    print(f"我的{
      
      animal_type}的名字是{
      
      pet_name}")
describ_pet('美媚')
describ_pet('美媚','猫')
describ_pet(animal_type='猫',pet_name='美媚')

insert image description here

3. The return value of the function

Instead of displaying output directly, a function can also process data and return a value or set of values. The value returned by the function becomes the return value.

3.1 Grammar

def xxxxx:
	  return xxx

eg:

def pingfang(num):
    return num**2
print(pingfang(2))

insert image description here

3.2 Make actual parameters optional (a certain actual parameter can be written or not)

For example, for example 威廉-嘿嘿嘿-查尔斯, there is a person whose name is composed of three parts, but other people have two characters 哈利-波特, so can you give a broad definition, that is, define a function, whether it is two characters It is still possible to correctly output the name of the person with three characters. The answer is of course yes.

How to achieve :

  • You can refer to the second part 给形参指定默认值, but at this time, an empty string is specified.
  • Add a knowledge point, that is, a non-empty string in python returns True, otherwise an empty string returns False;
def name(last_name,first_name,middle_name=''):
    if middle_name:
        full_name = f"你的名字是:{
      
      last_name}-{
      
      middle_name}-{
      
      first_name}"
    else:
        full_name = f"你的名字是:{
      
      last_name}{
      
      first_name}"
    return full_name
print(name('查尔斯','威廉','嘿嘿嘿'))
print(name('波特','哈利'))

insert image description here
ps: The return value of the function can be of any type, simply as mentioned above. Complex consists of lists, dictionaries and more.
eg:

def name(last_name,first_name,middle_name=''):
    if middle_name:
       message = {
    
    'first_name':first_name,
                  'middle_name':middle_name,
                  'last_name':last_name,
                  }
    else:
        message = {
    
    'first_name': first_name,
                   'last_name': last_name,
                   }
    return message
print(name('查尔斯','威廉','嘿嘿嘿'))
print(name('波特','哈利'))

insert image description here
ps: The same is true for lists, so I won’t repeat them here.

Guess you like

Origin blog.csdn.net/qq_63913621/article/details/129160093