Python basics: (6) function - function processing

1. Transfer list

When a list is passed to a function, the function can directly access its contents, which improves the efficiency of processing the list.

names = ['哈利波特','威廉','查尔斯']
def welcome(names):
    for name in names:
        print(f"你好{
      
      name},欢迎来到python世界!")
welcome(names)

insert image description here

1.1 Modify the list in the function

Once the list is passed to the function, the list can be modified, and this modification is permanent.

names = ['哈利波特','威廉','查尔斯']
delete = []

def copy(olds,news):
    while olds: #非空字符串为True
        news.append(olds.pop())

print('copy前:')
print(f"names:{
      
      names}")
print(f"delete:{
      
      delete}")
copy(names,delete)
print('copy后:')
print(f"names:{
      
      names}")
print(f"delete:{
      
      delete}")

insert image description here

1.2 Prohibited function modification list

It is forbidden, but in fact it is to create a new copy. To operate on this copy, the slice representation of the list can be used to [:]create a copy of the original list, but try not to create a copy, because it is time-consuming and labor-intensive.

names = ['哈利波特','威廉','查尔斯']
delete = []

def copy(olds,news):
    while olds:
        news.append(olds.pop())

print('copy前:')
print(f"names:{
      
      names}")
print(f"delete:{
      
      delete}")

"""在函数填写实参时,创建副本"""
copy(names[:],delete)

print('copy后:')
print(f"names:{
      
      names}")
print(f"delete:{
      
      delete}")

insert image description here

2. Pass any number of actual parameters

Sometimes you don't know how many actual parameters there are. At this time, you can use to *yuanzu_namecreate one 空元组and store it.

def by_cars(*cars): #使用*创建一个空元组
    for car in cars: #遍历元组
        print(f"I will by {
      
      car} in the future!")

by_cars('bmw','aodi','wuling')

insert image description here

2.1 Combining positional arguments with any number of arguments

If you want the function to receive different types of actual parameters, you must put the formal parameter that accepts any number of actual parameters (that is, *yuanzu_name) at the end of the function definition.

def by_cars(color,*cars): #使用*创建一个空元组
    for car in cars: #遍历元组
        print(f"I will by a {
      
      color} {
      
      car} in the future!")

by_cars('red','bmw','aodi','wuling')

insert image description here

2.2 Using any number of keyword arguments

Analogous to passing any number of arguments, creating an empty tuple, any number of keyword arguments is creating an empty dictionary, using **zidiancreate.

def message(name,**other_message):
    other_message['name'] = name
    return  other_message
"""注意此时的键值对中的'键'不需要添加引号!!"""
message_0 = message('mayahei',
        old = '20',
        tall = '100cm',
        )
print(message_0)

insert image description here

2.3 tips

You may encounter the following two descriptions:

  • *args: Collect any number of positional arguments

  • **kwargs: collect any number of keyword arguments

3. Storing functions in modules

  • One of the advantages of using functions is that you can separate your code from the main program. By giving the function a descriptive name, it is much easier for the main program to understand. You can go a step further and store functions in separate files called modules, and then import the modules into the main program.
  • The import statement allows code from a module to be used in the currently running program file.

3.1 Import the entire module

Put some functions in this section in a .py file, call it in the main function, and store this section in function.py.

def welcome(names):
    """打印你好xxx欢迎来到python世界"""
    for name in names:
        print(f"你好{
      
      name},欢迎来到python世界!")

def copy(olds,news):
    """把旧列表中的值copy到新列表"""
    while olds: #非空字符串为True
        news.append(olds.pop())

def by_cars(*cars): #使用*创建一个空元组
    """打印我将要买xx车"""
    for car in cars: #遍历元组
        print(f"I will by {
      
      car} in the future!")
        
def message(name,**other_message):
    """返回一个字典,其中包含所有的键值对信息"""
    other_message['name'] = name
    return  other_message
3.1.1 Then import this module in the main function.

Syntax : import xxx.py file name
example :

import function

insert image description here

3.2 Import specific functions

Grammar :

from 模块 import 函数名

Example :

from function import welcome

Only the welcome function can be called, and others cannot be called, otherwise an error will be reported.

from function import welcome
name = ['mayahei']
welcome(name)

insert image description here
insert image description here

3.3 Use as to assign an alias to the function

Syntax: Use as to specify an alias

from function import welcome as wl

insert image description here
insert image description here

3.4 Use as to assign an alias to the module

Same as specifying a function alias.

import function as fc

ps: At this time, the alias must be used to call the function. The function name
eg:

import function as fc
fc.welcome

insert image description here
insert image description here

3.5 Import all functions in the module

grammar:

from py文件名 import *
#因为此时所有函数都已经导入,所以直接可以使用函数。

insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/qq_63913621/article/details/129170979
Recommended