Clear, practical technology insights BSOD Code Lookup · Windows Error Code Lookup · Wi-Fi Troubleshooting · PC Troubleshooting Checklist

Functions in Python

Explore Functions in Python with clear explanations, practical examples, and useful tips.

Table of Contents

This guide covers functions in python with practical context and easy-to-follow details. Use it to understand the subject and apply the information confidently.

In Python, a function is a group of interrelated commands that are used to perform a specific task or task. The function helps divide the Python program into smaller blocks / sections / modules. When Python programs are too big, or need to expand, functions that help the program are more organized and manageable.

The function also has a very important effect: to avoid having to repeat the code to execute similar tasks, making the code more compact and reusable.

def ten_ham(các tham số/đối số):
 """Chuỗi văn bản để mô tả cho hàm (docstring)"""
 Các câu lệnh

Basically, a Python function definition will include the following components:

  1. Keyword def: Type in the beginning of the function title.
  2. Ten_ham: The unique identifier for the function. The naming of functions must comply with Python's name and identifier rules.
  3. Parameters / arguments: We pass the value to the function through these parameters. They are optional.
  4. Colons (: ): Mark the end of the function title.
  5. Docstring: Optional text string to describe the function of the function.
  6. Statements: One or more valid Python commands form a block of commands. These commands must have the same indentation level (usually 4 spaces).
  7. Return: This command is optional, used when the value from the function needs to be returned.

How the Function Works in Python

Here is a simple function definition, including the function name, function parameter, function description and a statement:

def chao(ten):
 """Hàm này dùng để 
 chào một người được truyền 
 vào như một tham số"""
 print("Xin chào, " + ten + "!")

Call the Function in Python

When a function has been defined, you can call it from another function, another program, or even at the command prompt. To call the function we just need to enter the function name with the appropriate parameters.

For example, to call the chao () function just defined above, we type the following command at the prompt:

>>> chao ("TipsMake.com")

We will get the following result:

You can also call this chao () function right in the code you are writing as shown below and the results will be the same as above:

Docstring in Python

The first string immediately after the function title is called docstring (documentation string), which is used to explain the function for the function. Although docstring is not required, the short explanation of the function of the function will help the user later, even you, to call the function to understand immediately what the function will do without having to find the definition again. Function to consider.

Adding documents to code is a good habit. There is no guarantee that after a few months back you can remember the details, clear the code you wrote earlier without error.

In the example above we have a docstring right below the function title. Docstring is usually written in pairs of 3 quotes. This string appears as a __doc__ attribute of the function.

To check the chao docstring () above, enter the following code and test it:

print (chao.__doc__)

Here are the results:

Return Command in Python Function

The return command is usually used to exit the function and return to the place where the function is called.

Syntax of return :

return [danh_sach_bieu_thuc]

This command may contain calculated expressions and return values. If there is no expression in the statement or no return command in the function, the function returns None.

Example of return:

def gia_tri_tuyet_doi(so):
 """Hàm này trả về giá trị tuyệt đối
 của một số nhập vào"""
 if so >= 0:
 return so
 else:
 return -so
# Đầu ra: 5
print(gia_tri_tuyet_doi(5))
# Đầu ra: 8
print(gia_tri_tuyet_doi(-8))
# Đầu ra: Giá trị tuyệt đối của số nhập vào
num=int(input("Nhập số cần lấy giá trị tuyệt đối: "))
print (gia_tri_tuyet_doi(num))

When running the above code, we get the following result:

5
8
Nhập số cần lấy giá trị tuyệt đối: -7
7

Range and Duration of Variables

The scope of the variable is the program segment where the variable is recognized. Parameters and variables are defined inside a function that cannot be "seen" from outside. Therefore, these variables and parameters only have scope in the function.

The lifetime of the variable is the amount of time that variable appears in memory. When the function is executed, the variable will exist.

The variable is destroyed when we exit the function. The function does not remember the value of the variable in the previous function calls.

def ham_in(): 
 x = 15 
 print("Giá trị bên trong hàm:",x)
x = 30 
 ham_in() 
 print("Giá trị bên ngoài hàm:",x)

In the above program, we use the same variable x, a variable inside the ham_in () function, an external variable x and executes the command to print these two values so that you realize the scope of the variable. The value of x we initialize is 30, although ham_in () has changed the value of x to 15, but it does not affect the value of x outside the function. When running the program, we get the result:

Giá trị bên trong hàm: 15
Giá trị bên ngoài hàm: 30

This is because the variable x inside the function is different from the variable x outside the function. Although they have the same name, they are actually two different variables with different ranges. The variable x in the function is a local variable, only effective in that function. The variable x outside the function is visible from within the function and has scope across the entire program.

With the variable outside the function, we can read the value of the variable in the function, but it cannot change its value. To change values for variables of this type, they must be declared as global variables using the global keyword.

Types of Functions in Python

Basically, Python has two main types of functions which are built-in functions in Python and user-defined functions. In the next articles, we will learn more about these two types of functions.

Python exercises have a prize

Previous article: Python loop techniques

FAQ

What should I check before following these steps?

Confirm device and software compatibility, save important data, and make sure you have the required permissions, files, and account access.

Why might the process not work?

Common causes include outdated software, missing permissions, incompatible hardware, an unstable connection, or completing a step in the wrong order.

Can I undo the changes if necessary?

That depends on the tool or setting. Use built-in restore options when available, keep a backup, and record the original configuration first.

Discussion

Reader Comments 0

Sign in with email or Google to join the discussion.