Hướng dẫn how do you access data from a function in python? - làm cách nào để bạn truy cập dữ liệu từ một hàm trong python?

Bạn không thể thấy giá trị của

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
1 vì nó chỉ được xác định cục bộ trong phạm vi của hàm
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
2, không phải trên toàn cầu, vì bạn đang cố gắng sử dụng nó khi gọi
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
3.

Show

Nếu bạn cần một giá trị để tồn tại bên ngoài phạm vi của hàm, bạn phải

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 nó đến nơi được gọi là hàm, như vậy:

def readfile(FILE):
    file = open(FILE, "r")
    file_data = file.read()
    file.close()
    return file_data

file_data = readfile("my_file.txt")
print(file_data)

Tôi cũng đề nghị sử dụng khối

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
5 khi thực hiện các hoạt động tệp. Đó là cách thực hành tốt nhất để đảm bảo xử lý tệp được đóng chính xác, ngay cả khi các ngoại lệ xảy ra. Điều này cải thiện việc xử lý bất kỳ lỗi nào mà hoạt động có thể gặp phải. Ví dụ:

def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)

Nếu bạn muốn truy cập từng dòng tệp, chúng tôi chỉ cần bao gồm một vòng

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
6 trong phạm vi
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
5. Ví dụ: in từng dòng của tệp:

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)

Xem bây giờ hướng dẫn này có một khóa học video liên quan được tạo bởi nhóm Python thực sự. Xem cùng với hướng dẫn bằng văn bản để hiểu sâu hơn về sự hiểu biết của bạn: Sử dụng câu lệnh Python Return một cách hiệu quả This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Using the Python return Statement Effectively

Câu lệnh Python

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 là một thành phần chính của các hàm và phương thức. Bạn có thể sử dụng câu lệnh
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 để làm cho các chức năng của bạn gửi các đối tượng Python trở lại mã người gọi. Các đối tượng này được gọi là giá trị trả về hàm. Bạn có thể sử dụng chúng để thực hiện tính toán thêm trong các chương trình của bạn.return value. You can use them to perform further computation in your programs.

Sử dụng câu lệnh

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 một cách hiệu quả là một kỹ năng cốt lõi nếu bạn muốn mã hóa các chức năng tùy chỉnh có pythonic và mạnh mẽ.

Trong hướng dẫn này, bạn sẽ học:

  • Cách sử dụng câu lệnh Python
    >>> def return_42():
    ...     return 42  # An explicit return statement
    ...
    
    >>> return_42()  # The caller code gets 42
    42
    
    4 trong các chức năng của bạnPython
    >>> def return_42():
    ...     return 42  # An explicit return statement
    ...
    
    >>> return_42()  # The caller code gets 42
    42
    
    4 statement
    in your functions
  • Cách trả về đơn hoặc nhiều giá trị từ các chức năng của bạnsingle or multiple values from your functions
  • Những thực hành tốt nhất cần quan sát khi sử dụng các tuyên bố
    >>> def return_42():
    ...     return 42  # An explicit return statement
    ...
    
    >>> return_42()  # The caller code gets 42
    42
    
    4best practices to observe when using
    >>> def return_42():
    ...     return 42  # An explicit return statement
    ...
    
    >>> return_42()  # The caller code gets 42
    42
    
    4 statements

Với kiến ​​thức này, bạn sẽ có thể viết các chức năng dễ đọc hơn, có thể duy trì và súc tích hơn trong Python. Nếu bạn hoàn toàn mới đối với các chức năng Python, thì bạn có thể kiểm tra xác định chức năng Python của riêng bạn trước khi đi sâu vào hướng dẫn này.

Bắt đầu với các chức năng Python

Hầu hết các ngôn ngữ lập trình cho phép bạn gán tên cho một khối mã thực hiện tính toán cụ thể. Các khối mã được đặt tên này có thể được sử dụng lại nhanh chóng vì bạn có thể sử dụng tên của chúng để gọi chúng từ các địa điểm khác nhau trong mã của bạn.

Các lập trình viên gọi các chương trình con, quy trình, quy trình hoặc chức năng được đặt tên này có tên này tùy thuộc vào ngôn ngữ họ sử dụng. Trong một số ngôn ngữ, có một sự khác biệt rõ ràng giữa một thói quen hoặc quy trình và một hàm.subroutines, routines, procedures, or functions depending on the language they use. In some languages, there’s a clear difference between a routine or procedure and a function.

Đôi khi sự khác biệt đó mạnh đến mức bạn cần sử dụng một từ khóa cụ thể để xác định quy trình hoặc chương trình con và từ khóa khác để xác định hàm. Ví dụ, ngôn ngữ lập trình cơ bản trực quan sử dụng

>>> num = return_42()
>>> num
42

>>> return_42() * 2
84

>>> return_42() + 5
47
3 và
>>> num = return_42()
>>> num
42

>>> return_42() * 2
84

>>> return_42() + 5
47
4 để phân biệt giữa hai.

Nói chung, một thủ tục là một khối mã được đặt tên thực hiện một tập hợp các hành động mà không tính toán giá trị hoặc kết quả cuối cùng. Mặt khác, một hàm là một khối mã được đặt tên thực hiện một số hành động với mục đích tính toán một giá trị hoặc kết quả cuối cùng, sau đó được gửi lại cho mã người gọi. Cả quy trình và chức năng có thể hành động dựa trên một tập hợp các giá trị đầu vào, thường được gọi là đối số.procedure is a named code block that performs a set of actions without computing a final value or result. On the other hand, a function is a named code block that performs some actions with the purpose of computing a final value or result, which is then sent back to the caller code. Both procedures and functions can act upon a set of input values, commonly known as arguments.

Trong Python, các loại khối mã được đặt tên này được gọi là chức năng vì chúng luôn gửi lại giá trị cho người gọi. Tài liệu Python xác định một chức năng như sau:

Một loạt các câu lệnh trả về một số giá trị cho người gọi. Nó cũng có thể được thông qua không hoặc nhiều đối số có thể được sử dụng trong việc thực hiện cơ thể. (Nguồn)

Mặc dù tài liệu chính thức nói rằng một hàm, trả về một số giá trị cho người gọi, nhưng bạn sẽ sớm thấy rằng các chức năng có thể trả về bất kỳ đối tượng Python nào cho mã người gọi.

Nói chung, một hàm có các đối số (nếu có), thực hiện một số hoạt động và trả về một giá trị (hoặc đối tượng). Giá trị mà một hàm trả về người gọi thường được gọi là giá trị trả về hàm. Tất cả các hàm Python có giá trị trả về, rõ ràng hoặc ẩn. Bạn sẽ bao gồm sự khác biệt giữa các giá trị trả về rõ ràng và ẩn sau này trong hướng dẫn này.takes arguments (if any), performs some operations, and returns a value (or object). The value that a function returns to the caller is generally known as the function’s return value. All Python functions have a return value, either explicit or implicit. You’ll cover the difference between explicit and implicit return values later in this tutorial.

Để viết hàm Python, bạn cần một tiêu đề bắt đầu bằng từ khóa

>>> num = return_42()
>>> num
42

>>> return_42() * 2
84

>>> return_42() + 5
47
5, theo sau là tên của hàm, một danh sách tùy chọn các đối số được phân tách bằng dấu phẩy bên trong một cặp dấu ngoặc đơn và dấu hai chấm cuối cùng.header that starts with the
>>> num = return_42()
>>> num
42

>>> return_42() * 2
84

>>> return_42() + 5
47
5 keyword, followed by the name of the function, an optional list of comma-separated arguments inside a required pair of parentheses, and a final colon.

Thành phần thứ hai của một hàm là khối mã hoặc cơ thể của nó. Python xác định các khối mã bằng cách sử dụng thụt lề thay vì dấu ngoặc,

>>> num = return_42()
>>> num
42

>>> return_42() * 2
84

>>> return_42() + 5
47
6 và
>>> num = return_42()
>>> num
42

>>> return_42() * 2
84

>>> return_42() + 5
47
7 từ khóa, v.v. Vì vậy, để xác định một hàm trong Python, bạn có thể sử dụng cú pháp sau:code block, or body. Python defines code blocks using indentation instead of brackets,
>>> num = return_42()
>>> num
42

>>> return_42() * 2
84

>>> return_42() + 5
47
6 and
>>> num = return_42()
>>> num
42

>>> return_42() * 2
84

>>> return_42() + 5
47
7 keywords, and so on. So, to define a function in Python you can use the following syntax:

def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass

Khi bạn mã hóa chức năng Python, bạn cần xác định tiêu đề với từ khóa

>>> num = return_42()
>>> num
42

>>> return_42() * 2
84

>>> return_42() + 5
47
5, tên của hàm và danh sách các đối số trong ngoặc đơn. Lưu ý rằng danh sách các đối số là tùy chọn, nhưng dấu ngoặc đơn được yêu cầu về mặt cú pháp. Sau đó, bạn cần xác định khối mã chức năng, sẽ bắt đầu một cấp độ thụt bên phải.

Trong ví dụ trên, bạn sử dụng câu lệnh

>>> num = return_42()
>>> num
42

>>> return_42() * 2
84

>>> return_42() + 5
47
9. Loại tuyên bố này rất hữu ích khi bạn cần một câu lệnh trình giữ chỗ trong mã của mình để làm cho nó chính xác về mặt cú pháp, nhưng bạn không cần phải thực hiện bất kỳ hành động nào. Các tuyên bố
>>> num = return_42()
>>> num
42

>>> return_42() * 2
84

>>> return_42() + 5
47
9 còn được gọi là hoạt động null vì họ không thực hiện bất kỳ hành động nào.null operation because they don’t perform any action.

Để sử dụng một chức năng, bạn cần gọi nó. Một cuộc gọi chức năng bao gồm tên hàm tên theo sau là các đối số chức năng trong ngoặc đơn:

function_name(arg1, arg2, ..., argN)

Bạn chỉ cần chuyển các đối số cho một cuộc gọi chức năng chỉ khi hàm yêu cầu chúng. Mặt khác, dấu ngoặc đơn luôn được yêu cầu trong một cuộc gọi chức năng. Nếu bạn quên chúng, thì bạn đã thắng được gọi chức năng nhưng tham khảo nó như một đối tượng chức năng.

Để làm cho các chức năng của bạn trả về một giá trị, bạn cần sử dụng câu lệnh Python

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4. Đó là những gì bạn có thể bao gồm từ thời điểm này.

Hiểu tuyên bố Python >>> def return_42(): ... return 42 # An explicit return statement ... >>> return_42() # The caller code gets 42 42 4

Câu lệnh Python

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 là một tuyên bố đặc biệt mà bạn có thể sử dụng bên trong một hàm hoặc phương thức để gửi kết quả của chức năng trở lại cho người gọi. Một câu lệnh
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 bao gồm từ khóa
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 theo sau là giá trị trả về tùy chọn.Python
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 statement
is a special statement that you can use inside a function or method to send the function’s result back to the caller. A
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 statement consists of the
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 keyword followed by an optional return value.

Giá trị trả về của hàm Python có thể là bất kỳ đối tượng Python nào. Tất cả mọi thứ trong Python là một đối tượng. Vì vậy, các chức năng của bạn có thể trả về các giá trị số (

>>> return 42
  File "", line 1
SyntaxError: 'return' outside function
6,
>>> return 42
  File "", line 1
SyntaxError: 'return' outside function
7 và
>>> return 42
  File "", line 1
SyntaxError: 'return' outside function
8), các bộ sưu tập và trình tự của các đối tượng (
>>> return 42
  File "", line 1
SyntaxError: 'return' outside function
9,
>>> def get_even(numbers):
...     even_nums = [num for num in numbers if not num % 2]
...     return even_nums
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
0,
>>> def get_even(numbers):
...     even_nums = [num for num in numbers if not num % 2]
...     return even_nums
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
1 hoặc
>>> def get_even(numbers):
...     even_nums = [num for num in numbers if not num % 2]
...     return even_nums
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
2 đối tượng)

Bạn có thể bỏ qua giá trị trả về của một hàm và sử dụng giá trị trả lại trần mà không có giá trị trả về. Bạn cũng có thể bỏ qua toàn bộ tuyên bố

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4. Trong cả hai trường hợp, giá trị trả lại sẽ là
>>> def get_even(numbers):
...     even_nums = [num for num in numbers if not num % 2]
...     return even_nums
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
5.

Trong hai phần tiếp theo, bạn sẽ bao gồm những điều cơ bản về cách thức câu lệnh

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 hoạt động và cách bạn có thể sử dụng nó để trả lại kết quả của chức năng trở lại mã người gọi.

Báo cáo rõ ràng >>> def return_42(): ... return 42 # An explicit return statement ... >>> return_42() # The caller code gets 42 42 4

Một câu lệnh

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 rõ ràng ngay lập tức chấm dứt thực thi chức năng và gửi giá trị trả về lại mã người gọi. Để thêm câu lệnh
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 rõ ràng vào hàm Python, bạn cần sử dụng
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 theo sau là giá trị trả về tùy chọn:explicit
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 statement
immediately terminates a function execution and sends the return value back to the caller code. To add an explicit
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 statement to a Python function, you need to use
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 followed by an optional return value:

>>>

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42

Khi bạn xác định

>>> def get_even(numbers):
...     return [num for num in numbers if not num % 2]
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
1, bạn sẽ thêm câu lệnh
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 rõ ràng (
>>> def get_even(numbers):
...     return [num for num in numbers if not num % 2]
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
3) ở cuối khối mã chức năng.
>>> def get_even(numbers):
...     return [num for num in numbers if not num % 2]
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
4 là giá trị trả về rõ ràng của
>>> def get_even(numbers):
...     return [num for num in numbers if not num % 2]
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
1. Điều này có nghĩa là bất cứ khi nào bạn gọi
>>> def get_even(numbers):
...     return [num for num in numbers if not num % 2]
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
1, chức năng sẽ gửi lại
>>> def get_even(numbers):
...     return [num for num in numbers if not num % 2]
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
4 cho người gọi.

Nếu bạn xác định một hàm với câu lệnh

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 rõ ràng có giá trị trả về rõ ràng, thì bạn có thể sử dụng giá trị trả về đó trong bất kỳ biểu thức nào:

>>>

>>> num = return_42()
>>> num
42

>>> return_42() * 2
84

>>> return_42() + 5
47

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42

Khi bạn xác định

>>> def get_even(numbers):
...     return [num for num in numbers if not num % 2]
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
1, bạn sẽ thêm câu lệnh
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 rõ ràng (
>>> def get_even(numbers):
...     return [num for num in numbers if not num % 2]
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
3) ở cuối khối mã chức năng.
>>> def get_even(numbers):
...     return [num for num in numbers if not num % 2]
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
4 là giá trị trả về rõ ràng của
>>> def get_even(numbers):
...     return [num for num in numbers if not num % 2]
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
1. Điều này có nghĩa là bất cứ khi nào bạn gọi
>>> def get_even(numbers):
...     return [num for num in numbers if not num % 2]
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
1, chức năng sẽ gửi lại
>>> def get_even(numbers):
...     return [num for num in numbers if not num % 2]
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
4 cho người gọi.

>>>

>>> return 42
  File "", line 1
SyntaxError: 'return' outside function

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42

Khi bạn xác định

>>> def get_even(numbers):
...     return [num for num in numbers if not num % 2]
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
1, bạn sẽ thêm câu lệnh
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 rõ ràng (
>>> def get_even(numbers):
...     return [num for num in numbers if not num % 2]
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
3) ở cuối khối mã chức năng.
>>> def get_even(numbers):
...     return [num for num in numbers if not num % 2]
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
4 là giá trị trả về rõ ràng của
>>> def get_even(numbers):
...     return [num for num in numbers if not num % 2]
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
1. Điều này có nghĩa là bất cứ khi nào bạn gọi
>>> def get_even(numbers):
...     return [num for num in numbers if not num % 2]
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
1, chức năng sẽ gửi lại
>>> def get_even(numbers):
...     return [num for num in numbers if not num % 2]
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
4 cho người gọi.

Nếu bạn xác định một hàm với câu lệnh

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 rõ ràng có giá trị trả về rõ ràng, thì bạn có thể sử dụng giá trị trả về đó trong bất kỳ biểu thức nào:

>>>

>>> def get_even(numbers):
...     even_nums = [num for num in numbers if not num % 2]
...     return even_nums
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42

Khi bạn xác định

>>> def get_even(numbers):
...     return [num for num in numbers if not num % 2]
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
1, bạn sẽ thêm câu lệnh
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 rõ ràng (
>>> def get_even(numbers):
...     return [num for num in numbers if not num % 2]
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
3) ở cuối khối mã chức năng.
>>> def get_even(numbers):
...     return [num for num in numbers if not num % 2]
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
4 là giá trị trả về rõ ràng của
>>> def get_even(numbers):
...     return [num for num in numbers if not num % 2]
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
1. Điều này có nghĩa là bất cứ khi nào bạn gọi
>>> def get_even(numbers):
...     return [num for num in numbers if not num % 2]
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
1, chức năng sẽ gửi lại
>>> def get_even(numbers):
...     return [num for num in numbers if not num % 2]
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
4 cho người gọi.

>>>

>>> def get_even(numbers):
...     return [num for num in numbers if not num % 2]
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42

Khi bạn xác định

>>> def get_even(numbers):
...     return [num for num in numbers if not num % 2]
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
1, bạn sẽ thêm câu lệnh
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 rõ ràng (
>>> def get_even(numbers):
...     return [num for num in numbers if not num % 2]
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
3) ở cuối khối mã chức năng.
>>> def get_even(numbers):
...     return [num for num in numbers if not num % 2]
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
4 là giá trị trả về rõ ràng của
>>> def get_even(numbers):
...     return [num for num in numbers if not num % 2]
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
1. Điều này có nghĩa là bất cứ khi nào bạn gọi
>>> def get_even(numbers):
...     return [num for num in numbers if not num % 2]
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
1, chức năng sẽ gửi lại
>>> def get_even(numbers):
...     return [num for num in numbers if not num % 2]
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
4 cho người gọi.

>>>

def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
0

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42

Khi bạn xác định >>> def get_even(numbers): ... return [num for num in numbers if not num % 2] ... >>> get_even([1, 2, 3, 4, 5, 6]) [2, 4, 6] 1, bạn sẽ thêm câu lệnh >>> def return_42(): ... return 42 # An explicit return statement ... >>> return_42() # The caller code gets 42 42 4 rõ ràng (>>> def get_even(numbers): ... return [num for num in numbers if not num % 2] ... >>> get_even([1, 2, 3, 4, 5, 6]) [2, 4, 6] 3) ở cuối khối mã chức năng. >>> def get_even(numbers): ... return [num for num in numbers if not num % 2] ... >>> get_even([1, 2, 3, 4, 5, 6]) [2, 4, 6] 4 là giá trị trả về rõ ràng của >>> def get_even(numbers): ... return [num for num in numbers if not num % 2] ... >>> get_even([1, 2, 3, 4, 5, 6]) [2, 4, 6] 1. Điều này có nghĩa là bất cứ khi nào bạn gọi >>> def get_even(numbers): ... return [num for num in numbers if not num % 2] ... >>> get_even([1, 2, 3, 4, 5, 6]) [2, 4, 6] 1, chức năng sẽ gửi lại >>> def get_even(numbers): ... return [num for num in numbers if not num % 2] ... >>> get_even([1, 2, 3, 4, 5, 6]) [2, 4, 6] 4 cho người gọi.

Nếu bạn xác định một hàm với câu lệnh

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 rõ ràng có giá trị trả về rõ ràng, thì bạn có thể sử dụng giá trị trả về đó trong bất kỳ biểu thức nào:

>>> def get_even(numbers):
...     return [num for num in numbers if not num % 2]
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
1 trả về giá trị số, bạn có thể sử dụng giá trị đó trong biểu thức toán học hoặc bất kỳ loại biểu thức nào khác trong đó giá trị có ý nghĩa hợp lý hoặc kết hợp. Đây là cách mã người gọi có thể tận dụng giá trị trả về hàm của hàm.implicit
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 statement
that uses
>>> def get_even(numbers):
...     even_nums = [num for num in numbers if not num % 2]
...     return even_nums
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
5 as a return value:

>>>

def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
1

Nếu bạn không cung cấp một câu lệnh

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 rõ ràng với giá trị trả về rõ ràng, thì Python sẽ cung cấp một câu lệnh
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 ngầm bằng cách sử dụng
>>> def get_even(numbers):
...     even_nums = [num for num in numbers if not num % 2]
...     return even_nums
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
5 làm giá trị trả lại. Trong ví dụ trên,
def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
26 thêm
def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
18 vào
def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
19 và lưu trữ giá trị trong
def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
29 nhưng nó không trả lại
def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
29. Đó là lý do tại sao bạn nhận được
def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
31 thay vì
def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
32. Để khắc phục sự cố, bạn cần phải
def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
33 hoặc trực tiếp
def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
34.

Một ví dụ về một hàm trả về

>>> def get_even(numbers):
...     even_nums = [num for num in numbers if not num % 2]
...     return even_nums
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
5 là
def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
36. Mục tiêu của hàm này là in các đối tượng vào tệp luồng văn bản, thường là đầu ra tiêu chuẩn (màn hình của bạn). Vì vậy, chức năng này không cần một câu lệnh
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 rõ ràng vì nó không trả lời bất cứ điều gì hữu ích hoặc có ý nghĩa:

>>>

def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
2

Cuộc gọi đến

def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
36 in
def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
39 lên màn hình. Vì đây là mục đích của
def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
36, chức năng không cần phải trả về bất cứ điều gì hữu ích, vì vậy bạn nhận được
>>> def get_even(numbers):
...     even_nums = [num for num in numbers if not num % 2]
...     return even_nums
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
5 như một giá trị trả về.

Bất kể các chức năng của bạn là bao lâu và phức tạp, bất kỳ chức năng nào không có câu lệnh

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 rõ ràng hoặc một chức năng có câu lệnh
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 mà không có giá trị trả về, sẽ trả về
>>> def get_even(numbers):
...     even_nums = [num for num in numbers if not num % 2]
...     return even_nums
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
5.

Trả lại vs in

Nếu bạn làm việc trong một phiên tương tác, thì bạn có thể nghĩ rằng in một giá trị và trả về một giá trị là các hoạt động tương đương. Xem xét hai chức năng sau và đầu ra của chúng:

>>>

def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
3

Cả hai chức năng dường như làm điều tương tự. Trong cả hai trường hợp, bạn thấy

def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
39 được in trên màn hình của bạn. Ở đó, chỉ có một sự khác biệt có thể nhìn thấy tinh tế, các dấu ngoặc kép duy nhất trong ví dụ thứ hai. Nhưng hãy xem những gì xảy ra nếu bạn trả về một kiểu dữ liệu khác, hãy nói một đối tượng
>>> return 42
  File "", line 1
SyntaxError: 'return' outside function
6:

>>>

def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
4

Bây giờ không có sự khác biệt có thể nhìn thấy. Trong cả hai trường hợp, bạn có thể thấy

>>> def get_even(numbers):
...     return [num for num in numbers if not num % 2]
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
4 trên màn hình của mình. Hành vi đó có thể gây nhầm lẫn nếu bạn chỉ bắt đầu với Python. Bạn có thể nghĩ rằng trả lại và in một giá trị là những hành động tương đương.

Bây giờ, giả sử bạn đang tiến sâu hơn vào Python và bạn bắt đầu viết kịch bản đầu tiên của mình. Bạn mở một trình soạn thảo văn bản và nhập mã sau:

def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
5

def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
48 lấy hai số, thêm chúng và trả về kết quả. Trên dòng 5, bạn gọi
def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
48 để tổng
def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
50 cộng với
def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
50. Vì bạn vẫn đang học sự khác biệt giữa trả lại và in một giá trị, bạn có thể mong đợi kịch bản của mình in
def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
52 lên màn hình. Tuy nhiên, đó không phải là những gì xảy ra, và bạn không nhận được gì trên màn hình của mình.line 5, you call
def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
48 to sum
def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
50 plus
def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
50. Since you’re still learning the difference between returning and printing a value, you might expect your script to print
def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
52 to the screen. However, that’s not what happens, and you get nothing on your screen.

Hãy thử nó một mình. Lưu tập lệnh của bạn vào một tệp có tên

def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
53 và chạy nó từ dòng lệnh của bạn như sau:

Nếu bạn chạy

def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
53 từ dòng lệnh của mình, thì bạn đã giành được bất kỳ kết quả nào trên màn hình của bạn. Điều đó bởi vì khi bạn chạy một tập lệnh, các giá trị trả về của các hàm mà bạn gọi trong tập lệnh don lồng được in lên màn hình như chúng làm trong một phiên tương tác.

Nếu bạn muốn tập lệnh của bạn hiển thị kết quả của việc gọi

def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
48 trên màn hình của bạn, thì bạn cần gọi rõ ràng
def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
36. Kiểm tra bản cập nhật sau của
def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
53:

def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
6

Bây giờ, khi bạn chạy

def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
53, bạn sẽ thấy số
def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
52 trên màn hình của bạn.

Vì vậy, nếu bạn làm việc trong một phiên tương tác, thì Python sẽ hiển thị kết quả của bất kỳ cuộc gọi chức năng nào trực tiếp đến màn hình của bạn. Nhưng nếu bạn đang viết một tập lệnh và bạn muốn xem một hàm giá trị trả về hàm, thì bạn cần sử dụng rõ ràng

def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
36.

Trả về nhiều giá trị

Bạn có thể sử dụng câu lệnh

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 để trả về nhiều giá trị từ một hàm. Để làm điều đó, bạn chỉ cần cung cấp một số giá trị trả về được phân tách bằng dấu phẩy.

Ví dụ: giả sử bạn cần viết một hàm lấy một mẫu dữ liệu số và trả về một bản tóm tắt các biện pháp thống kê. Để mã hóa chức năng đó, bạn có thể sử dụng mô -đun tiêu chuẩn Python

def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
62, cung cấp một số hàm để tính toán số liệu thống kê toán học của dữ liệu số.

Ở đây, một triển khai có thể thực hiện chức năng của bạn:

def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
7

Trong

def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
63, bạn tận dụng khả năng của Python, để trả về nhiều giá trị trong một câu lệnh
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 bằng cách trả về trung bình, trung bình và chế độ của mẫu cùng một lúc. Lưu ý rằng, để trả về nhiều giá trị, bạn chỉ cần viết chúng trong một danh sách được phân tách bằng dấu phẩy theo thứ tự bạn muốn chúng được trả về.

Khi bạn đã mã hóa

def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
63, bạn có thể tận dụng một tính năng Python mạnh mẽ được gọi là không thể giải nén để giải nén ba biện pháp thành ba biến tách biệt hoặc bạn chỉ có thể lưu trữ mọi thứ trong một biến:

>>>

def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
8

Ở đây, bạn giải nén ba giá trị trả về của

def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
63 vào các biến
def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
67,
def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
68 và
def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
69. Lưu ý rằng trong ví dụ cuối cùng, bạn lưu trữ tất cả các giá trị trong một biến duy nhất,
def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
70, hóa ra là Python
>>> def get_even(numbers):
...     even_nums = [num for num in numbers if not num % 2]
...     return even_nums
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
0.

Hàm tích hợp

def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
72 cũng là một ví dụ về hàm trả về nhiều giá trị. Hàm lấy hai số (không phức tạp) làm đối số và trả về hai số, thương số của hai giá trị đầu vào và phần còn lại của bộ phận:

>>>

def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
9

Cuộc gọi đến

def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
72 trả về một tuple chứa thương số và phần còn lại là kết quả của việc chia hai số không phức tạp được cung cấp dưới dạng đối số. Đây là một ví dụ về một hàm có nhiều giá trị trả về.

Sử dụng tuyên bố Python >>> def return_42(): ... return 42 # An explicit return statement ... >>> return_42() # The caller code gets 42 42 4: Thực tiễn tốt nhất

Cho đến nay, bạn đã đề cập đến những điều cơ bản về cách thức tuyên bố của Python

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4. Bây giờ bạn biết cách viết các chức năng trả về một hoặc nhiều giá trị cho người gọi. Ngoài ra, bạn đã học được rằng nếu bạn không thêm một câu lệnh
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 rõ ràng với giá trị trả về rõ ràng cho một hàm đã cho, thì Python sẽ thêm nó cho bạn. Giá trị đó sẽ là
>>> def get_even(numbers):
...     even_nums = [num for num in numbers if not num % 2]
...     return even_nums
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
5.

Trong phần này, bạn sẽ bao gồm một số ví dụ sẽ hướng dẫn bạn thông qua một tập hợp các thực tiễn lập trình tốt để sử dụng hiệu quả câu lệnh

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4. Những thực tiễn này sẽ giúp bạn viết các chức năng dễ đọc hơn, có thể duy trì, mạnh mẽ và hiệu quả hơn trong Python.

Trả lại >>> def get_even(numbers): ... even_nums = [num for num in numbers if not num % 2] ... return even_nums ... >>> get_even([1, 2, 3, 4, 5, 6]) [2, 4, 6] 5 một cách rõ ràng

Một số lập trình viên dựa vào tuyên bố

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 ngầm mà Python thêm vào bất kỳ chức năng nào mà không có một chức năng rõ ràng. Điều này có thể gây nhầm lẫn cho các nhà phát triển đến từ các ngôn ngữ lập trình khác trong đó một hàm không có giá trị trả về được gọi là thủ tục.procedure.

Có những tình huống trong đó bạn có thể thêm một

def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
81 rõ ràng vào các chức năng của bạn. Tuy nhiên, trong các tình huống khác, bạn có thể dựa vào hành vi mặc định của Python:

  • Nếu chức năng của bạn thực hiện các hành động nhưng không có giá trị

    >>> def return_42():
    ...     return 42  # An explicit return statement
    ...
    
    >>> return_42()  # The caller code gets 42
    42
    
    4 rõ ràng và hữu ích, thì bạn có thể bỏ qua trả lại
    >>> def get_even(numbers):
    ...     even_nums = [num for num in numbers if not num % 2]
    ...     return even_nums
    ...
    
    >>> get_even([1, 2, 3, 4, 5, 6])
    [2, 4, 6]
    
    5 vì làm điều đó sẽ là thừa và khó hiểu. Bạn cũng có thể sử dụng giá trị trả lại mà không có giá trị trả về chỉ để làm rõ ý định của bạn trở về từ chức năng.

  • Nếu chức năng của bạn có nhiều câu lệnh

    >>> def return_42():
    ...     return 42  # An explicit return statement
    ...
    
    >>> return_42()  # The caller code gets 42
    42
    
    4 và trả về
    >>> def get_even(numbers):
    ...     even_nums = [num for num in numbers if not num % 2]
    ...     return even_nums
    ...
    
    >>> get_even([1, 2, 3, 4, 5, 6])
    [2, 4, 6]
    
    5 là một tùy chọn hợp lệ, thì bạn nên xem xét việc sử dụng rõ ràng
    def writefile(FILE, DATA):
        data = str(DATA) 
    
        with open(FILE, 'w') as write_stream:
            write_stream.write(data)
    
    def readfile(FILE):
        with open(FILE, 'r') as read_stream:
            file_data = read_stream.read()
    
        return file_data
    
    file_data = readfile("my_file.txt")
    print(file_data)
    
    81 thay vì dựa vào hành vi mặc định của Python.

Những thực hành này có thể cải thiện khả năng đọc và khả năng duy trì của mã của bạn bằng cách truyền đạt rõ ràng ý định của bạn.

Khi nói đến việc trả lại

>>> def get_even(numbers):
...     even_nums = [num for num in numbers if not num % 2]
...     return even_nums
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
5, bạn có thể sử dụng một trong ba phương pháp có thể:

  1. Bỏ qua câu lệnh
    >>> def return_42():
    ...     return 42  # An explicit return statement
    ...
    
    >>> return_42()  # The caller code gets 42
    42
    
    4 và dựa vào hành vi mặc định là trả về
    >>> def get_even(numbers):
    ...     even_nums = [num for num in numbers if not num % 2]
    ...     return even_nums
    ...
    
    >>> get_even([1, 2, 3, 4, 5, 6])
    [2, 4, 6]
    
    5.
  2. Sử dụng giá trị trả lại mà không có giá trị trả về, cũng trả về
    >>> def get_even(numbers):
    ...     even_nums = [num for num in numbers if not num % 2]
    ...     return even_nums
    ...
    
    >>> get_even([1, 2, 3, 4, 5, 6])
    [2, 4, 6]
    
    5.
  3. Trả lại
    >>> def get_even(numbers):
    ...     even_nums = [num for num in numbers if not num % 2]
    ...     return even_nums
    ...
    
    >>> get_even([1, 2, 3, 4, 5, 6])
    [2, 4, 6]
    
    5 một cách rõ ràng.

Ở đây, cách thức hoạt động của nó trong thực tế:

>>>

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
0

Có hay không trả lại

>>> def get_even(numbers):
...     even_nums = [num for num in numbers if not num % 2]
...     return even_nums
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
5 một cách rõ ràng là một quyết định cá nhân. Tuy nhiên, bạn nên xem xét rằng trong một số trường hợp, một
def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
81 rõ ràng có thể tránh các vấn đề về khả năng duy trì. Điều này đặc biệt đúng đối với các nhà phát triển đến từ các ngôn ngữ lập trình khác mà don hành xử như Python.

Ghi nhớ giá trị trả về

Khi viết các chức năng tùy chỉnh, bạn có thể vô tình quên trả về giá trị từ một hàm. Trong trường hợp này, Python sẽ trả lại

>>> def get_even(numbers):
...     even_nums = [num for num in numbers if not num % 2]
...     return even_nums
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
5 cho bạn. Điều này có thể khiến các lỗi tinh tế có thể khó khăn cho một nhà phát triển Python khởi đầu để hiểu và gỡ lỗi.

Bạn có thể tránh vấn đề này bằng cách viết câu lệnh

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 ngay sau khi tiêu đề của hàm. Sau đó, bạn có thể thực hiện một đường chuyền thứ hai để viết cơ thể chức năng. Dưới đây, một mẫu mà bạn có thể sử dụng khi mã hóa các chức năng Python của mình:

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
1

Nếu bạn đã quen với việc bắt đầu các chức năng của mình như thế này, thì rất có thể bạn sẽ không bỏ lỡ câu lệnh

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 nữa. Với cách tiếp cận này, bạn có thể viết phần thân của hàm, kiểm tra nó và đổi tên các biến khi bạn biết rằng hàm hoạt động.

Thực tiễn này có thể tăng năng suất của bạn và làm cho các chức năng của bạn ít dễ bị lỗi hơn. Nó cũng có thể giúp bạn tiết kiệm rất nhiều thời gian gỡ lỗi.

Tránh các biểu thức phức tạp

Như bạn đã thấy trước đây, nó là một thực tế phổ biến để sử dụng kết quả của một biểu thức làm giá trị trả về trong các hàm Python. Nếu biểu thức mà bạn sử dụng trở nên quá phức tạp, thì thực tế này có thể dẫn đến các chức năng khó hiểu, gỡ lỗi và duy trì.

Ví dụ: nếu bạn đang thực hiện một tính toán phức tạp, thì sẽ dễ đọc hơn để tính toán kết quả cuối cùng bằng cách sử dụng các biến tạm thời với các tên có ý nghĩa.temporary variables with meaningful names.

Xem xét chức năng sau đây tính toán phương sai của mẫu dữ liệu số:

>>>

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
2

Biểu thức mà bạn sử dụng ở đây khá phức tạp và khó hiểu. Nó cũng khó gỡ lỗi vì bạn đã thực hiện nhiều hoạt động trong một biểu thức duy nhất. Để giải quyết vấn đề cụ thể này, bạn có thể tận dụng phương pháp phát triển gia tăng giúp cải thiện khả năng đọc của chức năng.

Hãy xem thực hiện thay thế sau đây của

def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
99:

>>>

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
3

Trong lần thực hiện thứ hai này của

def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
99, bạn tính toán phương sai trong một số bước. Mỗi bước được thể hiện bằng một biến tạm thời với một tên có ý nghĩa.

Các biến tạm thời như

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
01,
def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
67 và
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
03 thường hữu ích khi gỡ lỗi mã của bạn. Ví dụ, nếu có điều gì đó không ổn với một trong số họ, thì bạn có thể gọi
def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
36 để biết những gì xảy ra trước khi câu lệnh
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 chạy.

Nói chung, bạn nên tránh sử dụng các biểu thức phức tạp trong câu lệnh

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 của bạn. Thay vào đó, bạn có thể chia mã của mình thành nhiều bước và sử dụng các biến tạm thời cho mỗi bước. Sử dụng các biến tạm thời có thể làm cho mã của bạn dễ dàng gỡ lỗi, hiểu và duy trì hơn.

Trả về giá trị so với Globals sửa đổi

Các chức năng mà don lồng có một tuyên bố

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 rõ ràng với giá trị trả về có ý nghĩa thường là các hành động có hình thức có tác dụng phụ. Chẳng hạn, một tác dụng phụ có thể in một cái gì đó lên màn hình, sửa đổi biến toàn cầu, cập nhật trạng thái của một đối tượng, viết một số văn bản vào một tệp, v.v.side effect can be, for example, printing something to the screen, modifying a global variable, updating the state of an object, writing some text to a file, and so on.

Sửa đổi các biến toàn cầu thường được coi là một thực hành lập trình xấu. Cũng giống như các chương trình có biểu thức phức tạp, các chương trình sửa đổi các biến toàn cầu có thể khó gỡ lỗi, hiểu và duy trì.

Khi bạn sửa đổi một biến toàn cầu, bạn có khả năng ảnh hưởng đến tất cả các chức năng, lớp, đối tượng và bất kỳ phần nào khác trong các chương trình của bạn dựa vào biến toàn cầu đó.

Để hiểu một chương trình sửa đổi các biến toàn cầu, bạn cần nhận thức được tất cả các phần của chương trình có thể thấy, truy cập và thay đổi các biến đó. Vì vậy, thực tiễn tốt khuyến nghị viết các chức năng độc lập có một số đối số và trả về một giá trị (hoặc giá trị) hữu ích mà không gây ra bất kỳ tác dụng phụ nào đối với các biến toàn cầu.self-contained functions that take some arguments and return a useful value (or values) without causing any side effect on global variables.

Ngoài ra, các chức năng với câu lệnh

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 rõ ràng trả về giá trị có ý nghĩa dễ kiểm tra hơn so với các hàm sửa đổi hoặc cập nhật các biến toàn cầu.

Ví dụ sau đây cho thấy một hàm thay đổi một biến toàn cầu. Hàm sử dụng câu lệnh

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
09, cũng được coi là một thực tiễn lập trình xấu trong Python:

>>>

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
4

Trong ví dụ này, trước tiên bạn tạo một biến toàn cầu,

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
10, với giá trị ban đầu là
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
11. Bên trong
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
12, bạn sử dụng câu lệnh
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
09 để cho biết chức năng rằng bạn muốn sửa đổi một biến toàn cầu. Tuyên bố cuối cùng tăng
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
10 bởi
def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
18.

Kết quả của việc gọi

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
12 sẽ phụ thuộc vào giá trị ban đầu của
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
10. Các giá trị ban đầu khác nhau cho
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
10 sẽ tạo ra các kết quả khác nhau, do đó, kết quả của hàm có thể được kiểm soát bởi chính hàm.

Để tránh loại hành vi này, bạn có thể viết một

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
12 khép kín, lấy các đối số và trả về một giá trị mạch lạc chỉ phụ thuộc vào các đối số đầu vào:

>>>

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
5

Bây giờ kết quả của việc gọi

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
12 chỉ phụ thuộc vào các đối số đầu vào thay vì vào giá trị ban đầu của
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
10. Điều này làm cho chức năng mạnh mẽ và dễ kiểm tra hơn.

Ngoài ra, khi bạn cần cập nhật

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
10, bạn có thể thực hiện rõ ràng với một cuộc gọi đến
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
12. Bằng cách này, bạn sẽ có nhiều quyền kiểm soát hơn đối với những gì xảy ra với
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
10 trong suốt mã của bạn.

Nói chung, nó là một thực tiễn tốt để tránh các chức năng sửa đổi các biến toàn cầu. Nếu có thể, hãy cố gắng viết các chức năng độc lập với một câu lệnh

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 rõ ràng trả về một giá trị mạch lạc và có ý nghĩa.self-contained functions with an explicit
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 statement that returns a coherent and meaningful value.

Sử dụng >>> def return_42(): ... return 42 # An explicit return statement ... >>> return_42() # The caller code gets 42 42 4 với các điều kiện

Các hàm Python không bị hạn chế để có một tuyên bố

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 duy nhất. Nếu một hàm nhất định có nhiều hơn một câu lệnh
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4, thì mô hình đầu tiên gặp phải sẽ xác định kết thúc thực thi chức năng và cả giá trị trả về của nó.

Một cách phổ biến để viết các chức năng với nhiều câu lệnh

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 là sử dụng các câu lệnh có điều kiện cho phép bạn cung cấp các câu lệnh
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 khác nhau tùy thuộc vào kết quả của việc đánh giá một số điều kiện.

Giả sử bạn cần mã hóa một hàm lấy một số và trả về giá trị tuyệt đối của nó. Nếu số lớn hơn

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
11, thì bạn sẽ trả về cùng một số. Nếu số nhỏ hơn
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
11, thì bạn sẽ trả về giá trị đối diện hoặc không âm.

Ở đây, một triển khai có thể cho chức năng này:

>>>

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
6

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
33 có hai tuyên bố
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 rõ ràng, mỗi câu trong số chúng được bọc trong tuyên bố
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
35 của riêng mình. Nó cũng có một tuyên bố
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 ngầm. Nếu
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
37 xảy ra là
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
11, thì không có điều kiện nào là đúng và chức năng kết thúc mà không nhấn bất kỳ câu lệnh
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 rõ ràng nào. Khi điều này xảy ra, bạn tự động nhận được
>>> def get_even(numbers):
...     even_nums = [num for num in numbers if not num % 2]
...     return even_nums
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
5.

Hãy xem cuộc gọi sau đây đến

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
33 bằng cách sử dụng
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
11 làm đối số:

>>>

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
7

Khi bạn gọi

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
33 bằng cách sử dụng
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
11 làm đối số, kết quả là bạn sẽ nhận được
>>> def get_even(numbers):
...     even_nums = [num for num in numbers if not num % 2]
...     return even_nums
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
5. Điều đó bởi vì dòng thực thi đi đến cuối hàm mà không đạt được bất kỳ tuyên bố
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 rõ ràng nào. Thật không may, giá trị tuyệt đối của
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
11 là
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
11, không phải
>>> def get_even(numbers):
...     even_nums = [num for num in numbers if not num % 2]
...     return even_nums
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
5.

Để khắc phục sự cố này, bạn có thể thêm câu lệnh

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 thứ ba, trong một mệnh đề
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
51 mới hoặc trong một điều khoản
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
52 cuối cùng:

>>>

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
8

Khi bạn gọi

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
33 bằng cách sử dụng
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
11 làm đối số, kết quả là bạn sẽ nhận được
>>> def get_even(numbers):
...     even_nums = [num for num in numbers if not num % 2]
...     return even_nums
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
5. Điều đó bởi vì dòng thực thi đi đến cuối hàm mà không đạt được bất kỳ tuyên bố
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 rõ ràng nào. Thật không may, giá trị tuyệt đối của
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
11 là
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
11, không phải
>>> def get_even(numbers):
...     even_nums = [num for num in numbers if not num % 2]
...     return even_nums
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
5.

Để khắc phục sự cố này, bạn có thể thêm câu lệnh

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 thứ ba, trong một mệnh đề
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
51 mới hoặc trong một điều khoản
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
52 cuối cùng:

>>>

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
9

Khi bạn gọi

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
33 bằng cách sử dụng
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
11 làm đối số, kết quả là bạn sẽ nhận được
>>> def get_even(numbers):
...     even_nums = [num for num in numbers if not num % 2]
...     return even_nums
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
5. Điều đó bởi vì dòng thực thi đi đến cuối hàm mà không đạt được bất kỳ tuyên bố
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 rõ ràng nào. Thật không may, giá trị tuyệt đối của
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
11 là
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
11, không phải
>>> def get_even(numbers):
...     even_nums = [num for num in numbers if not num % 2]
...     return even_nums
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
5.

Để khắc phục sự cố này, bạn có thể thêm câu lệnh

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 thứ ba, trong một mệnh đề
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
51 mới hoặc trong một điều khoản
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
52 cuối cùng:

Bây giờ, def readfile(FILE): with open(FILE, 'r') as read_stream: for line in read_stream print(line) 33 kiểm tra mọi điều kiện có thể, def readfile(FILE): with open(FILE, 'r') as read_stream: for line in read_stream print(line) 54, def readfile(FILE): with open(FILE, 'r') as read_stream: for line in read_stream print(line) 55 và def readfile(FILE): with open(FILE, 'r') as read_stream: for line in read_stream print(line) 56. Mục đích của ví dụ này là chỉ ra rằng khi bạn sử dụng các câu lệnh có điều kiện để cung cấp nhiều câu lệnh >>> def return_42(): ... return 42 # An explicit return statement ... >>> return_42() # The caller code gets 42 42 4, bạn cần đảm bảo rằng mọi tùy chọn có thể đều có câu lệnh >>> def return_42(): ... return 42 # An explicit return statement ... >>> return_42() # The caller code gets 42 42 4 riêng. Nếu không, chức năng của bạn sẽ có một lỗi ẩn.

Cuối cùng, bạn có thể thực hiện

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
33 một cách ngắn gọn, hiệu quả và pythonic hơn bằng cách sử dụng một câu lệnh
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
35:

Trong trường hợp này, chức năng của bạn nhấn vào câu lệnh

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 đầu tiên nếu
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
55. Trong tất cả các trường hợp khác, cho dù
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
54 hay
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
56, nó sẽ đạt được câu lệnh
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 thứ hai. Với triển khai mới này, chức năng của bạn trông tốt hơn rất nhiều. Nó dễ đọc hơn, súc tích và hiệu quả hơn.

>>>

def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
0

Nếu bạn sử dụng các câu lệnh

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
35 để cung cấp một số câu lệnh
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4, thì bạn không cần một điều khoản
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
52 để bao gồm điều kiện cuối cùng. Chỉ cần thêm một câu lệnh
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 ở cuối khối mã chức năng và ở cấp độ đầu tiên của thụt.

Trở về

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
70 hoặc
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
71

  • Một trường hợp sử dụng phổ biến khác cho sự kết hợp của các câu lệnh
    def readfile(FILE):
        with open(FILE, 'r') as read_stream:
            for line in read_stream
                print(line)
    
    35 và
    >>> def return_42():
    ...     return 42  # An explicit return statement
    ...
    
    >>> return_42()  # The caller code gets 42
    42
    
    4 là khi bạn mã hóa một hàm có giá trị vị ngữ hoặc boolean. Loại chức năng này trả về
    def readfile(FILE):
        with open(FILE, 'r') as read_stream:
            for line in read_stream
                print(line)
    
    70 hoặc
    def readfile(FILE):
        with open(FILE, 'r') as read_stream:
            for line in read_stream
                print(line)
    
    71 theo một điều kiện nhất định.
  • Ví dụ: giả sử bạn cần viết một hàm lấy hai số nguyên,
    def readfile(FILE):
        with open(FILE, 'r') as read_stream:
            for line in read_stream
                print(line)
    
    76 và
    def readfile(FILE):
        with open(FILE, 'r') as read_stream:
            for line in read_stream
                print(line)
    
    77 và trả về
    def readfile(FILE):
        with open(FILE, 'r') as read_stream:
            for line in read_stream
                print(line)
    
    70 nếu
    def readfile(FILE):
        with open(FILE, 'r') as read_stream:
            for line in read_stream
                print(line)
    
    76 chia hết cho
    def readfile(FILE):
        with open(FILE, 'r') as read_stream:
            for line in read_stream
                print(line)
    
    77. Nếu không, chức năng sẽ trả về
    def readfile(FILE):
        with open(FILE, 'r') as read_stream:
            for line in read_stream
                print(line)
    
    71. Đây là một triển khai có thể:
  • def readfile(FILE):
        with open(FILE, 'r') as read_stream:
            for line in read_stream
                print(line)
    
    82 Trả về
    def readfile(FILE):
        with open(FILE, 'r') as read_stream:
            for line in read_stream
                print(line)
    
    70 Nếu phần còn lại chia
    def readfile(FILE):
        with open(FILE, 'r') as read_stream:
            for line in read_stream
                print(line)
    
    76 cho
    def readfile(FILE):
        with open(FILE, 'r') as read_stream:
            for line in read_stream
                print(line)
    
    77 bằng
    def readfile(FILE):
        with open(FILE, 'r') as read_stream:
            for line in read_stream
                print(line)
    
    11. Nếu không, nó trả về
    def readfile(FILE):
        with open(FILE, 'r') as read_stream:
            for line in read_stream
                print(line)
    
    71. Lưu ý rằng trong Python, giá trị
    def readfile(FILE):
        with open(FILE, 'r') as read_stream:
            for line in read_stream
                print(line)
    
    11 là giả, vì vậy bạn cần sử dụng toán tử
    def readfile(FILE):
        with open(FILE, 'r') as read_stream:
            for line in read_stream
                print(line)
    
    89 để phủ nhận giá trị sự thật của điều kiện.
  • Đôi khi, bạn sẽ viết các chức năng vị ngữ liên quan đến các nhà khai thác như sau:

Các toán tử so sánh

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
90,
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
91,
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
92,
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
93,
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
94 và
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
95

>>>

def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
1

Nhà điều hành thành viên

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
96

Toán tử nhận dạng

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
97

>>>

def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
2

Nhà điều hành Boolean

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
89

Trong những trường hợp này, bạn có thể trực tiếp sử dụng biểu thức boolean trong câu lệnh

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 của mình. Điều này là có thể bởi vì các toán tử này trả về
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
70 hoặc
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
71. Theo ý tưởng này, ở đây, một triển khai mới của
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
82:

>>>

def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
3

Nếu

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
76 chia hết cho
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
77, thì
def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
05 trả về
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
11, đó là giả mạo trong Python. Vì vậy, để trả về
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
70, bạn cần sử dụng toán tử
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
89.

  1. Mặt khác, nếu bạn cố gắng sử dụng các điều kiện liên quan đến các nhà khai thác Boolean như
    def function_name(arg1, arg2,..., argN):
        # Function's code goes here...
        pass
    
    09 và
    def function_name(arg1, arg2,..., argN):
        # Function's code goes here...
        pass
    
    10 theo cách bạn đã thấy trước đây, thì các chức năng vị ngữ của bạn đã giành được công việc chính xác. Điều đó bởi vì các nhà khai thác này hành xử khác nhau. Họ trả lại một trong các toán hạng trong điều kiện thay vì
    def readfile(FILE):
        with open(FILE, 'r') as read_stream:
            for line in read_stream
                print(line)
    
    70 hoặc
    def readfile(FILE):
        with open(FILE, 'r') as read_stream:
            for line in read_stream
                print(line)
    
    71:
  2. Nói chung,
    def function_name(arg1, arg2,..., argN):
        # Function's code goes here...
        pass
    
    10 trả về toán hạng sai đầu tiên hoặc toán hạng cuối cùng. Mặt khác,
    def function_name(arg1, arg2,..., argN):
        # Function's code goes here...
        pass
    
    09 trả về toán hạng thực sự đầu tiên hoặc toán hạng cuối cùng. Vì vậy, để viết một vị từ liên quan đến một trong những toán tử này, bạn sẽ cần sử dụng câu lệnh
    def readfile(FILE):
        with open(FILE, 'r') as read_stream:
            for line in read_stream
                print(line)
    
    35 rõ ràng hoặc cuộc gọi đến chức năng tích hợp
    def function_name(arg1, arg2,..., argN):
        # Function's code goes here...
        pass
    
    16.
  3. Giả sử bạn muốn viết một hàm vị ngữ lấy hai giá trị và trả về
    def readfile(FILE):
        with open(FILE, 'r') as read_stream:
            for line in read_stream
                print(line)
    
    70 nếu cả hai đều đúng và
    def readfile(FILE):
        with open(FILE, 'r') as read_stream:
            for line in read_stream
                print(line)
    
    71 khác. Ở đây, cách tiếp cận đầu tiên của bạn đối với chức năng này:

def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
10 trả về các toán hạng thay vì
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
70 hoặc
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
71, chức năng của bạn không hoạt động chính xác. Có ít nhất ba khả năng để khắc phục sự cố này:

>>>

def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
4

Một tuyên bố rõ ràng

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
35

Mặt khác, nếu bạn sử dụng biểu thức có điều kiện Python hoặc toán tử ternary, thì bạn có thể viết chức năng vị ngữ của mình như sau:

>>>

def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
5

Ở đây, bạn sử dụng một biểu thức có điều kiện để cung cấp giá trị trả về cho

def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
24. Biểu thức có điều kiện được đánh giá là
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
70 nếu cả
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
76 và
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
77 là sự thật. Mặt khác, kết quả cuối cùng là
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
71.

Cuối cùng, nếu bạn sử dụng

def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
16, thì bạn có thể mã
def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
24 như sau:

>>>

def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
6

Ở đây, bạn sử dụng một biểu thức có điều kiện để cung cấp giá trị trả về cho

def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
24. Biểu thức có điều kiện được đánh giá là
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
70 nếu cả
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
76 và
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
77 là sự thật. Mặt khác, kết quả cuối cùng là
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
71.

Cuối cùng, nếu bạn sử dụng def function_name(arg1, arg2,..., argN): # Function's code goes here... pass 16, thì bạn có thể mã def function_name(arg1, arg2,..., argN): # Function's code goes here... pass 24 như sau:

def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
16 Trả về
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
70 nếu
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
76 và
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
77 là đúng và
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
71 khác. Nó tùy thuộc vào bạn những gì cách tiếp cận để sử dụng để giải quyết vấn đề này. Tuy nhiên, giải pháp thứ hai có vẻ dễ đọc hơn. Bạn nghĩ sao?short-circuit. It breaks the loop execution and makes the function return immediately. To better understand this behavior, you can write a function that emulates
def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
44. This built-in function takes an iterable and returns
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
70 if at least one of its items is truthy.

Các vòng ngắn mạch

>>>

def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
7

Ở đây, bạn sử dụng một biểu thức có điều kiện để cung cấp giá trị trả về cho

def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
24. Biểu thức có điều kiện được đánh giá là
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
70 nếu cả
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
76 và
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
77 là sự thật. Mặt khác, kết quả cuối cùng là
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
71.

Cuối cùng, nếu bạn sử dụng

def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
16, thì bạn có thể mã
def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
24 như sau:short-circuit evaluation. For example, suppose that you pass an iterable that contains a million items. If the first item in that iterable happens to be true, then the loop runs only one time rather than a million times. This can save you a lot of processing time when running your code.

def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
16 Trả về
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
70 nếu
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
76 và
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
77 là đúng và
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
71 khác. Nó tùy thuộc vào bạn những gì cách tiếp cận để sử dụng để giải quyết vấn đề này. Tuy nhiên, giải pháp thứ hai có vẻ dễ đọc hơn. Bạn nghĩ sao?

Các vòng ngắn mạch

Một câu lệnh

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 bên trong một vòng lặp thực hiện một số loại ngắn mạch. Nó phá vỡ thực thi vòng lặp và làm cho chức năng trở lại ngay lập tức. Để hiểu rõ hơn về hành vi này, bạn có thể viết một hàm mô phỏng
def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
44. Chức năng tích hợp này có thể lặp lại và trả về
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
70 nếu ít nhất một trong số các mục của nó là sự thật.dead code. The Python interpreter totally ignores dead code when running your functions. So, having that kind of code in a function is useless and confusing.

Để mô phỏng

def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
44, bạn có thể mã hóa một hàm như sau:

>>>

def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
8

Nếu bất kỳ

def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
47 trong
def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
48 là đúng, thì dòng thực thi đi vào khối
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
35. Câu lệnh
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 phá vỡ vòng lặp và trả về ngay lập tức với giá trị trả về
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
70. Nếu không có giá trị trong
def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
48 là đúng, thì
def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
53 trả về
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
71.

Hàm này thực hiện đánh giá ngắn mạch. Ví dụ, giả sử rằng bạn vượt qua một điều có thể chứa một triệu vật phẩm. Nếu mục đầu tiên trong đó có thể xảy ra là đúng, thì vòng lặp chỉ chạy một lần thay vì một triệu lần. Điều này có thể giúp bạn tiết kiệm rất nhiều thời gian xử lý khi chạy mã của bạn.

>>>

def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
9

Điều quan trọng cần lưu ý là để sử dụng câu lệnh

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 bên trong một vòng lặp, bạn cần kết thúc câu lệnh trong một câu lệnh
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
35. Nếu không, vòng lặp sẽ luôn bị vỡ trong lần lặp đầu tiên của nó.

Nhận ra mã chết

Ngay khi một hàm nhấn vào câu lệnh

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4, nó sẽ chấm dứt mà không thực thi bất kỳ mã tiếp theo nào. Do đó, mã xuất hiện sau tuyên bố chức năng ____ ____54 thường được gọi là mã chết. Trình thông dịch Python hoàn toàn bỏ qua mã chết khi chạy các chức năng của bạn. Vì vậy, có loại mã đó trong một hàm là vô dụng và khó hiểu.

Xem xét chức năng sau, thêm mã sau câu lệnh

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4:

  1. Tuyên bố
    def function_name(arg1, arg2,..., argN):
        # Function's code goes here...
        pass
    
    60 trong ví dụ này sẽ không bao giờ thực thi vì câu lệnh đó xuất hiện sau câu lệnh của hàm
    >>> def return_42():
    ...     return 42  # An explicit return statement
    ...
    
    >>> return_42()  # The caller code gets 42
    42
    
    4. Xác định mã chết và xóa nó là một thực tế tốt mà bạn có thể áp dụng để viết các chức năng tốt hơn.
    holds the name of the tuple-like class that you’re creating. It needs to be a string.
  2. Điều đáng chú ý là nếu bạn sử dụng các câu lệnh có điều kiện để cung cấp nhiều câu lệnh
    >>> def return_42():
    ...     return 42  # An explicit return statement
    ...
    
    >>> return_42()  # The caller code gets 42
    42
    
    4, thì bạn có thể có mã sau tuyên bố
    >>> def return_42():
    ...     return 42  # An explicit return statement
    ...
    
    >>> return_42()  # The caller code gets 42
    42
    
    4 cho thấy won đã chết miễn là nó bên ngoài tuyên bố
    def readfile(FILE):
        with open(FILE, 'r') as read_stream:
            for line in read_stream
                print(line)
    
    35:
    holds the names of the fields or attributes of the tuple-like class. It can be a sequence of strings such as
    def function_name(arg1, arg2,..., argN):
        # Function's code goes here...
        pass
    
    79 or a single string with each name separated by whitespace or commas, such as
    def function_name(arg1, arg2,..., argN):
        # Function's code goes here...
        pass
    
    80 or
    def function_name(arg1, arg2,..., argN):
        # Function's code goes here...
        pass
    
    81.

Mặc dù cuộc gọi đến

def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
36 là sau tuyên bố
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4, nhưng nó không phải là mã chết. Khi
def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
67 được đánh giá thành
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
71, cuộc gọi
def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
36 được chạy và bạn nhận được
def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
39 được in lên màn hình của bạn.

function_name(arg1, arg2, ..., argN)
0

Trả lại nhiều đối tượng được đặt tên

Khi bạn viết một hàm trả về nhiều giá trị trong một câu lệnh

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4, bạn có thể xem xét sử dụng đối tượng
def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
72 để làm cho các hàm của bạn dễ đọc hơn.
def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
73 là một lớp bộ sưu tập trả về một lớp con của
>>> def get_even(numbers):
...     even_nums = [num for num in numbers if not num % 2]
...     return even_nums
...

>>> get_even([1, 2, 3, 4, 5, 6])
[2, 4, 6]
0 có các trường hoặc thuộc tính. Bạn có thể truy cập các thuộc tính đó bằng cách sử dụng ký hiệu DOT hoặc thao tác lập chỉ mục.

Ở đây, cách thức hoạt động của

def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
63:

>>>

function_name(arg1, arg2, ..., argN)
1

Khi bạn gọi

def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
63 với một mẫu dữ liệu số, bạn sẽ nhận được một đối tượng
def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
73 chứa trung bình, trung bình và chế độ của mẫu. Lưu ý rằng bạn có thể truy cập từng phần tử của bộ tuple bằng cách sử dụng ký hiệu DOT hoặc thao tác lập chỉ mục.

Cuối cùng, bạn cũng có thể sử dụng một thao tác giải nén có thể lặp lại để lưu trữ từng giá trị trong biến độc lập của riêng nó.

Chức năng trả lại: Đóng cửa

Trong Python, các chức năng là các đối tượng hạng nhất. Đối tượng hạng nhất là một đối tượng có thể được gán cho một biến, được truyền dưới dạng đối số cho một hàm hoặc được sử dụng làm giá trị trả về trong một hàm. Vì vậy, bạn có thể sử dụng một đối tượng hàm làm giá trị trả về trong bất kỳ câu lệnh

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 nào.

Một hàm có chức năng làm đối số, kết quả là trả về một hàm hoặc cả hai đều là hàm bậc cao hơn. Chức năng của nhà máy đóng cửa là một ví dụ phổ biến về chức năng bậc cao trong Python. Loại chức năng này có một số đối số và trả về một hàm bên trong. Hàm bên trong thường được gọi là đóng cửa.closure.

Một đóng cửa mang thông tin về phạm vi thực thi kèm theo của nó. Điều này cung cấp một cách để giữ lại thông tin trạng thái giữa các cuộc gọi chức năng. Các chức năng của nhà máy đóng cửa là hữu ích khi bạn cần viết mã dựa trên khái niệm đánh giá lười biếng hoặc bị trì hoãn.

Giả sử bạn cần viết một hàm trợ giúp có một số và trả về kết quả của việc nhân số đó với một yếu tố nhất định. Bạn có thể mã hóa chức năng đó như sau:

function_name(arg1, arg2, ..., argN)
2

def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
98 lấy
def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
99 và
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
37 làm đối số và trả lại sản phẩm của họ. Vì
def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
99 hiếm khi thay đổi trong ứng dụng của bạn, bạn thấy khó chịu khi cung cấp cùng một yếu tố trong mọi cuộc gọi chức năng. Vì vậy, bạn cần một cách để giữ lại trạng thái hoặc giá trị của
def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
99 giữa các cuộc gọi đến
def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
98 và chỉ thay đổi nó khi cần. Để giữ lại giá trị hiện tại của
def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
99 giữa các cuộc gọi, bạn có thể sử dụng đóng cửa.

Việc triển khai sau đây của

def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
98 sử dụng đóng cửa để giữ lại giá trị của
def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
99 giữa các cuộc gọi:

>>>

function_name(arg1, arg2, ..., argN)
3

Khi bạn gọi

def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
63 với một mẫu dữ liệu số, bạn sẽ nhận được một đối tượng
def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
73 chứa trung bình, trung bình và chế độ của mẫu. Lưu ý rằng bạn có thể truy cập từng phần tử của bộ tuple bằng cách sử dụng ký hiệu DOT hoặc thao tác lập chỉ mục.

Cuối cùng, bạn cũng có thể sử dụng một thao tác giải nén có thể lặp lại để lưu trữ từng giá trị trong biến độc lập của riêng nó.

Chức năng trả lại: Đóng cửa

>>>

function_name(arg1, arg2, ..., argN)
4

Trong Python, các chức năng là các đối tượng hạng nhất. Đối tượng hạng nhất là một đối tượng có thể được gán cho một biến, được truyền dưới dạng đối số cho một hàm hoặc được sử dụng làm giá trị trả về trong một hàm. Vì vậy, bạn có thể sử dụng một đối tượng hàm làm giá trị trả về trong bất kỳ câu lệnh

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 nào.

Một hàm có chức năng làm đối số, kết quả là trả về một hàm hoặc cả hai đều là hàm bậc cao hơn. Chức năng của nhà máy đóng cửa là một ví dụ phổ biến về chức năng bậc cao trong Python. Loại chức năng này có một số đối số và trả về một hàm bên trong. Hàm bên trong thường được gọi là đóng cửa.

Một đóng cửa mang thông tin về phạm vi thực thi kèm theo của nó. Điều này cung cấp một cách để giữ lại thông tin trạng thái giữa các cuộc gọi chức năng. Các chức năng của nhà máy đóng cửa là hữu ích khi bạn cần viết mã dựa trên khái niệm đánh giá lười biếng hoặc bị trì hoãn.decorator function takes a function object as an argument and returns a function object. The decorator processes the decorated function in some way and returns it or replaces it with another function or callable object.

Giả sử bạn cần viết một hàm trợ giúp có một số và trả về kết quả của việc nhân số đó với một yếu tố nhất định. Bạn có thể mã hóa chức năng đó như sau:

def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
98 lấy
def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
99 và
def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        for line in read_stream
            print(line)
37 làm đối số và trả lại sản phẩm của họ. Vì
def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
99 hiếm khi thay đổi trong ứng dụng của bạn, bạn thấy khó chịu khi cung cấp cùng một yếu tố trong mọi cuộc gọi chức năng. Vì vậy, bạn cần một cách để giữ lại trạng thái hoặc giá trị của
def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
99 giữa các cuộc gọi đến
def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
98 và chỉ thay đổi nó khi cần. Để giữ lại giá trị hiện tại của
def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
99 giữa các cuộc gọi, bạn có thể sử dụng đóng cửa.

>>>

function_name(arg1, arg2, ..., argN)
5

Việc triển khai sau đây của

def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
98 sử dụng đóng cửa để giữ lại giá trị của
def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
99 giữa các cuộc gọi:

Bên trong

def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
98, bạn xác định một hàm bên trong được gọi là
function_name(arg1, arg2, ..., argN)
08 và trả lại mà không gọi nó. Đối tượng chức năng bạn trả về là một đóng cửa giữ lại thông tin về trạng thái của
def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
99. Nói cách khác, nó nhớ giá trị của
def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
99 giữa các cuộc gọi. Đó là lý do tại sao
function_name(arg1, arg2, ..., argN)
11 nhớ rằng
def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
99 bằng với
def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
50 và
function_name(arg1, arg2, ..., argN)
14 nhớ rằng
def function_name(arg1, arg2,..., argN):
    # Function's code goes here...
    pass
99 bằng
function_name(arg1, arg2, ..., argN)
16.

Lưu ý rằng bạn có thể tự do sử dụng lại

function_name(arg1, arg2, ..., argN)
11 và
function_name(arg1, arg2, ..., argN)
14 vì họ không quên thông tin trạng thái tương ứng của họ.

Các ví dụ phổ biến khác về các nhà trang trí trong Python là

function_name(arg1, arg2, ..., argN)
41,
function_name(arg1, arg2, ..., argN)
42 và
function_name(arg1, arg2, ..., argN)
43. Nếu bạn muốn đi sâu hơn vào các nhà trang trí Python, thì hãy xem Primer trên các nhà trang trí Python. Bạn cũng có thể kiểm tra các nhà trang trí Python 101.

Trả về các đối tượng do người dùng xác định: mẫu nhà máy

Câu lệnh Python

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 cũng có thể trả về các đối tượng do người dùng xác định. Nói cách khác, bạn có thể sử dụng các đối tượng tùy chỉnh của riêng mình làm giá trị trả về trong một hàm. Một trường hợp sử dụng phổ biến cho khả năng này là mô hình nhà máy.

Mẫu nhà máy xác định một giao diện để tạo các đối tượng trên con ruồi để đáp ứng với các điều kiện mà bạn có thể dự đoán khi bạn viết một chương trình. Bạn có thể triển khai một nhà máy của các đối tượng do người dùng xác định bằng cách sử dụng một chức năng lấy một số đối số khởi tạo và trả về các đối tượng khác nhau theo đầu vào cụ thể.

Giả sử bạn viết một ứng dụng vẽ. Bạn cần tạo các hình dạng khác nhau khi bay để đáp ứng với các lựa chọn của người dùng. Chương trình của bạn sẽ có hình vuông, vòng tròn, hình chữ nhật, v.v. Để tạo ra những hình dạng đó một cách nhanh chóng, trước tiên bạn cần tạo các lớp hình dạng mà bạn sẽ sử dụng:

function_name(arg1, arg2, ..., argN)
6

Khi bạn có một lớp cho mỗi hình dạng, bạn có thể viết một hàm có tên của hình dạng dưới dạng chuỗi và danh sách các đối số tùy chọn (

function_name(arg1, arg2, ..., argN)
45) và đối số từ khóa (
function_name(arg1, arg2, ..., argN)
46) để tạo và khởi tạo hình dạng khi bay:

function_name(arg1, arg2, ..., argN)
7

Hàm này tạo ra một thể hiện hình dạng cụ thể và trả lại cho người gọi. Bây giờ bạn có thể sử dụng

function_name(arg1, arg2, ..., argN)
47 để tạo các đối tượng có hình dạng khác nhau để đáp ứng nhu cầu của người dùng:

>>>

function_name(arg1, arg2, ..., argN)
8

Nếu bạn gọi

function_name(arg1, arg2, ..., argN)
47 với tên của hình dạng cần thiết dưới dạng chuỗi, thì bạn sẽ nhận được một thể hiện mới về hình dạng phù hợp với
function_name(arg1, arg2, ..., argN)
49 mà bạn đã chuyển đến nhà máy.

Sử dụng >>> def return_42(): ... return 42 # An explicit return statement ... >>> return_42() # The caller code gets 42 42 4 trong function_name(arg1, arg2, ..., argN) 51 Khối function_name(arg1, arg2, ..., argN) 52

Khi bạn sử dụng câu lệnh

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 bên trong câu lệnh
function_name(arg1, arg2, ..., argN)
51 với mệnh đề
function_name(arg1, arg2, ..., argN)
52, mệnh đề
function_name(arg1, arg2, ..., argN)
52 luôn được thực thi trước câu lệnh
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4. Điều này đảm bảo rằng mã trong mệnh đề
function_name(arg1, arg2, ..., argN)
52 sẽ luôn chạy. Kiểm tra ví dụ sau:

>>>

function_name(arg1, arg2, ..., argN)
9

Nếu bạn gọi

function_name(arg1, arg2, ..., argN)
47 với tên của hình dạng cần thiết dưới dạng chuỗi, thì bạn sẽ nhận được một thể hiện mới về hình dạng phù hợp với
function_name(arg1, arg2, ..., argN)
49 mà bạn đã chuyển đến nhà máy.

Sử dụng >>> def return_42(): ... return 42 # An explicit return statement ... >>> return_42() # The caller code gets 42 42 4 trong function_name(arg1, arg2, ..., argN) 51 Khối function_name(arg1, arg2, ..., argN) 52

Khi bạn sử dụng câu lệnh

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 bên trong câu lệnh
function_name(arg1, arg2, ..., argN)
51 với mệnh đề
function_name(arg1, arg2, ..., argN)
52, mệnh đề
function_name(arg1, arg2, ..., argN)
52 luôn được thực thi trước câu lệnh
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4. Điều này đảm bảo rằng mã trong mệnh đề
function_name(arg1, arg2, ..., argN)
52 sẽ luôn chạy. Kiểm tra ví dụ sau:generator function. When you call a generator function, it returns a generator iterator. So, you can say that a generator function is a generator factory.

Khi bạn gọi

function_name(arg1, arg2, ..., argN)
59, bạn sẽ được chuyển đổi thành số dấu phẩy động hoặc một đối tượng chuỗi. Trước khi làm điều đó, chức năng của bạn chạy mệnh đề
function_name(arg1, arg2, ..., argN)
52 và in một thông báo lên màn hình của bạn. Bất cứ mã nào bạn thêm vào mệnh đề
function_name(arg1, arg2, ..., argN)
52 sẽ được thực thi trước khi hàm chạy câu lệnh
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4.

Sử dụng

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 trong các chức năng của máy phát

>>>

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
0

Nếu bạn gọi

function_name(arg1, arg2, ..., argN)
47 với tên của hình dạng cần thiết dưới dạng chuỗi, thì bạn sẽ nhận được một thể hiện mới về hình dạng phù hợp với
function_name(arg1, arg2, ..., argN)
49 mà bạn đã chuyển đến nhà máy.

Sử dụng

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 trong
function_name(arg1, arg2, ..., argN)
51 Khối
function_name(arg1, arg2, ..., argN)
52

Khi bạn sử dụng câu lệnh >>> def return_42(): ... return 42 # An explicit return statement ... >>> return_42() # The caller code gets 42 42 4 bên trong câu lệnh function_name(arg1, arg2, ..., argN) 51 với mệnh đề function_name(arg1, arg2, ..., argN) 52, mệnh đề function_name(arg1, arg2, ..., argN) 52 luôn được thực thi trước câu lệnh >>> def return_42(): ... return 42 # An explicit return statement ... >>> return_42() # The caller code gets 42 42 4. Điều này đảm bảo rằng mã trong mệnh đề function_name(arg1, arg2, ..., argN) 52 sẽ luôn chạy. Kiểm tra ví dụ sau:

Khi bạn gọi

function_name(arg1, arg2, ..., argN)
59, bạn sẽ được chuyển đổi thành số dấu phẩy động hoặc một đối tượng chuỗi. Trước khi làm điều đó, chức năng của bạn chạy mệnh đề
function_name(arg1, arg2, ..., argN)
52 và in một thông báo lên màn hình của bạn. Bất cứ mã nào bạn thêm vào mệnh đề
function_name(arg1, arg2, ..., argN)
52 sẽ được thực thi trước khi hàm chạy câu lệnh
>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4.

Sử dụng

>>> def return_42():
...     return 42  # An explicit return statement
...

>>> return_42()  # The caller code gets 42
42
4 trong các chức năng của máy phát

  • Hàm Python với câu lệnh
    function_name(arg1, arg2, ..., argN)
    
    65 trong cơ thể của nó là một hàm máy phát. Khi bạn gọi một hàm trình tạo, nó sẽ trả về một trình lặp lại máy phát. Vì vậy, bạn có thể nói rằng một chức năng máy phát là một nhà máy máy phát.Python
    >>> def return_42():
    ...     return 42  # An explicit return statement
    ...
    
    >>> return_42()  # The caller code gets 42
    42
    
    4 statement
    in your functions
  • Bạn có thể sử dụng câu lệnh
    >>> def return_42():
    ...     return 42  # An explicit return statement
    ...
    
    >>> return_42()  # The caller code gets 42
    42
    
    4 bên trong hàm trình tạo để chỉ ra rằng trình tạo đã được thực hiện. Tuyên bố
    >>> def return_42():
    ...     return 42  # An explicit return statement
    ...
    
    >>> return_42()  # The caller code gets 42
    42
    
    4 sẽ làm cho trình tạo tăng
    function_name(arg1, arg2, ..., argN)
    
    68. Giá trị trả về sẽ được truyền dưới dạng đối số cho trình khởi tạo của
    function_name(arg1, arg2, ..., argN)
    
    68 và sẽ được gán cho thuộc tính
    function_name(arg1, arg2, ..., argN)
    
    70 của nó.single or multiple values from your functions to the caller code
  • Ở đây, một trình tạo mang lại
    def writefile(FILE, DATA):
        data = str(DATA) 
    
        with open(FILE, 'w') as write_stream:
            write_stream.write(data)
    
    def readfile(FILE):
        with open(FILE, 'r') as read_stream:
            file_data = read_stream.read()
    
        return file_data
    
    file_data = readfile("my_file.txt")
    print(file_data)
    
    18 và
    def writefile(FILE, DATA):
        data = str(DATA) 
    
        with open(FILE, 'w') as write_stream:
            write_stream.write(data)
    
    def readfile(FILE):
        with open(FILE, 'r') as read_stream:
            file_data = read_stream.read()
    
        return file_data
    
    file_data = readfile("my_file.txt")
    print(file_data)
    
    50 theo yêu cầu và sau đó trả về
    function_name(arg1, arg2, ..., argN)
    
    16:best practices when using the
    >>> def return_42():
    ...     return 42  # An explicit return statement
    ...
    
    >>> return_42()  # The caller code gets 42
    42
    
    4 statement

function_name(arg1, arg2, ..., argN)
74 Trả về một đối tượng Trình tạo mang lại
def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
18 và
def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
50 theo yêu cầu. Để truy xuất từng số biểu mẫu đối tượng Trình tạo, bạn có thể sử dụng
function_name(arg1, arg2, ..., argN)
77, đây là chức năng tích hợp để truy xuất mục tiếp theo từ Trình tạo Python.

Hai cuộc gọi đầu tiên đến

function_name(arg1, arg2, ..., argN)
77 truy xuất lần lượt
def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
18 và
def writefile(FILE, DATA):
    data = str(DATA) 

    with open(FILE, 'w') as write_stream:
        write_stream.write(data)

def readfile(FILE):
    with open(FILE, 'r') as read_stream:
        file_data = read_stream.read()

    return file_data

file_data = readfile("my_file.txt")
print(file_data)
50. Trong cuộc gọi thứ ba, máy phát điện đã kiệt sức và bạn nhận được
function_name(arg1, arg2, ..., argN)
68. Lưu ý rằng giá trị trả về của hàm máy phát (
function_name(arg1, arg2, ..., argN)
16) trở thành thuộc tính
function_name(arg1, arg2, ..., argN)
70 của đối tượng
function_name(arg1, arg2, ..., argN)
68. This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Using the Python return Statement Effectively

Làm thế nào để bạn lấy dữ liệu từ một hàm trong Python?

Bạn có thể đặt câu lệnh trả về ở cuối hàm để trả về các biến (ReadVar trong trường hợp này) (và bạn hầu như luôn luôn nên). Sau đó, bạn có thể gán đối số được trả về (ReadVar) cho một biến mới (ví dụ: RV). Bạn cũng có thể cho nó cùng tên.put a return statement at the end of a function to return variables ( readvar in this case) (and you almost always should). Then you can assign the returned argument ( readvar ) to a new variable (e.g. rv ). You can also give it the same name.

Làm thế nào để bạn truy cập các chức năng trong Python?

Bốn bước để xác định một hàm trong Python là như sau:..
Sử dụng từ khóa def để khai báo chức năng và theo dõi tên này với tên chức năng ..
Thêm tham số vào hàm: Chúng nên nằm trong dấu ngoặc đơn của hàm.....
Thêm các câu lệnh mà các chức năng nên thực thi ..

Làm thế nào để bạn gọi dữ liệu từ chức năng này sang chức năng khác trong Python?

Biến có thể được gán cho đối tượng hàm bên trong phần thân hàm.Vì vậy, biến chỉ tồn tại sau khi hàm được gọi.Khi hàm đã được gọi, biến sẽ được liên kết với đối tượng hàm.

Làm thế nào để bạn thực hiện một chức năng trong Python?

Để sử dụng các hàm trong Python, bạn viết tên hàm (hoặc biến trỏ đến đối tượng hàm) theo sau là dấu ngoặc đơn (để gọi hàm).Nếu hàm đó chấp nhận các đối số (như hầu hết các hàm), thì bạn sẽ chuyển các đối số bên trong dấu ngoặc đơn khi bạn gọi hàm.write the function name (or the variable that points to the function object) followed by parentheses (to call the function). If that function accepts arguments (as most functions do), then you'll pass the arguments inside the parentheses as you call the function.