Python Basics (5): Definition and Calling of Functions

Python Basics (4): Learning and Examples of Basic Data Types

foreword

Function is an important concept in Python programming. Mastering the use and design of functions can improve the 编程效率和代码质量function. The functions of functions are as follows:

  1. 代码重用和模块化:functions make it possible to encapsulate a piece of reusable code into a function that can be called multiple times in different parts of the program. This can 避免重复编写相同improve the code of the code 可维护性和可读性. Functions also support modular programming, decomposing the program into multiple small modules, and each function is responsible for completing a specific task, making the program structure clearer, easier to understand and maintain.

  2. 抽象和封装: Functions can abstract complex operations into a function call, 隐藏实现细节. This provides a higher level of abstraction, resulting in cleaner, easier to use and maintain code. The encapsulation of functions also allows a series of operations to be grouped together and processed as a unit.

  3. 参数传递和返回值: Functions can accept parameters as input and perform corresponding operations based on the values ​​of the parameters. Through the parameters of the function, data and information can be passed to the function, so that the function can adapt to different input situations. Functions can also returnreturn calculation results or other required values ​​through statements, so that the function can pass the results to the caller for use in other parts of the program.

  4. 代码可读性和可维护性: Encapsulating a piece of code in a function can make the code more readable and easy to understand. The use of functions can provide meaningful function names and appropriate comments, thereby increasing the readability of the code. In addition, functions make the program structure clearer, easier to maintain and debug. When an error occurs, only specific functions need to be checked rather than the entire program.

  5. 分解复杂任务和可测试性: The function can decompose a complex task into multiple small functions, and each function is responsible for solving a part of the problem. This reduces the difficulty of writing complex code and makes problems easier to manage and solve. The modular nature of functions also makes unit testing easier. Each function can be tested independently to ensure its functional correctness without testing the entire program.

1. Python function example

# 这个函数名为 `greet`,它接受一个参数 `name`。函数体内部打印了一条包含参数 `name` 的问候语。
def greet(name):
    """
    这个函数用于向用户打招呼
    """
    print("Hello, " + name + "!")

# 调用函数
greet("CXK")

insert image description here

2. Custom functions

2.1 Function Syntax

In Python, deffunctions are defined using the keyword. A function definition includes a function name, parameters, and a function body.

def function_name(parameter1, parameter2, ...):
    # 函数体
    # 执行任务
    # 返回结果(可选)
  • function_nameis the name of the function, should have 描述性, and conform to Python 命名规范. (I like to define the method named menthod1() or func() suggestioncall yourself
  • parameter1, parameter2, ...is the parameter list of the function. Parameters are optional, you can define as many parameters as you want. Parameters can be required, default, or variable.
  • A function body is a block of code that performs a specific task. Can contain any number of statements.
  • Use returnthe statement to return a result. If the function has no returnstatement, it will return by default None.

2.2 Function Example

def add_numbers(a, b):
    """
    这个函数接受两个参数,并返回它们的和
    """
    result = a + b
    return result

# 调用函数
sum = add_numbers(3, 5)
print(sum)  # 输出 8

The function takes two arguments aand breturns their sum. Inside the body of the function , aand are badded and the result is stored in the variable result. Use returnthe statement to return result.
insert image description here

2.3 Function calls

Calling a function means executing the code inside the function body. To call a function, simply provide the function name and the required parameters

function_name(argument1, argument2, ...)
  • function_nameis the name of the function
  • argument1, argument2, ...is the actual parameter value provided when the function is called

In the above example, we called greet("cxk")and add_numbers(3, 5), passing different parameters respectively

3. Built-in functions

The following are some commonly used built-in functions. For a detailed list of functions, please refer to the official Python documentation.

Classification and examples of built-in functions in Python according to their functions:

3.1 Mathematical functions

  • abs(): Returns the absolute value of a number.
print(abs(-10))  # 输出:10
  • pow(): Returns a value raised to the specified power.
print(pow(2, 3))  # 输出:8
  • round(): Rounds the value.
print(round(3.14159, 2))  # 输出:3.14

3.2 Type conversion function

  • int(): Converts the value to an integer type.
print(int("10"))  # 输出:10
  • float(): Convert the value to a float type.
print(float("3.14"))  # 输出:3.14
  • str(): Convert the value to string type.
print(str(42))  # 输出:"42"

3.3 Sequence operation function

  • len(): Returns the length or number of elements of the sequence object.
print(len("Hello"))  # 输出:5
  • max(): Returns the maximum value in the sequence object.
print(max([5, 2, 9, 1, 7]))  # 输出:9
  • min(): Returns the minimum value in the sequence object.
print(min([5, 2, 9, 1, 7]))  # 输出:1
  • sum(): Calculates the sum of all elements in the sequence object.
print(sum([1, 2, 3, 4, 5]))  # 输出:15

3.4 Input and output functions

  • print(): Print out the specified content.
print("Hello, World!")  # 输出:Hello, World!
  • input(): Read a line of text from user input.
name = input("Enter your name: ")
print("Hello, " + name)

3.5 File operation functions

  • open(): Open a file and return a file object.
file = open("example.txt", "r")
  • read(): Read the file content.
content = file.read()
  • write(): Write content to a file.
file.write("Hello, World!")
  • close(): Close the file.
file.close()

3.6 Iterator functions

  • range(): Generates a sequence of integers.
print(list(range(1, 6)))  # 输出:[1, 2, 3, 4, 5]
  • enumerate(): Enumerates the sequence object and returns the index and corresponding element.
for index, value in enumerate(['song', 'jump', 'rap']):
    print(index, value)

3.7 Set operation functions

  • set(): Creates an unordered collection of unique elements.
my_set = set([1, 2, 3, 2, 4, 5])
print(my_set)  # 输出:{1, 2, 3, 4, 5}
  • len(): Returns the number of elements in the collection.
print(len(my_set))  # 输出:5
  • union(): Returns the union of two collections.
set1 = {
    
    1, 2, 3}
set2 = {
    
    3, 4, 5}
print(set1.union(set2))  # 输出:{1, 2, 3, 4, 5}

3.8 String manipulation functions

  • len(): Returns the length of the string.
print(len("Hello"))  # 输出:5
  • upper(): Converts a string to uppercase.
print("Hello".upper())  # 输出:HELLO
  • lower(): Convert a string to lowercase.
print("Hello".lower())  # 输出:hello
  • split(): Split the string into a list of substrings.
words = "Hello, World!".split(", ")
print(words)  # 输出:['Hello', 'World!']

Guess you like

Origin blog.csdn.net/qq_29864051/article/details/131348253