Functions in Python
What is Python function? How is the syntax, components, and function types in Python? How to create functions in Python? These questions will be answered in the Python lesson below.
What is Python function?
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.
The syntax of Python functions
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:
- Keyword def : Type in the beginning of the function title.
- ten_ham : The unique identifier for the function. The naming of functions must comply with Python's name and identifier rules.
- Parameters / arguments : We pass the value to the function through these parameters. They are optional.
- Colons ( :) : Mark the end of the function title.
- docstring : Optional text string to describe the function of the function.
- Statements : One or more valid Python commands form a block of commands. These commands must have the same indentation level (usually 4 spaces).
- Return : This command is optional, used when the value from the function needs to be returned.
How the function works in Python:
Example of Python function
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 will appear 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
You should read it
May be interested
- Module time in Pythonpython has a time module used to handle time-related tasks. tipsmake.com will work with you to find out the details and functions related to the time specified in this module. let's follow it!
- Help () function in Pythonthe built-in help () function in python is used to display documents and invoke the help system of modules, functions, classes, keywords ...
- Multiple choice quiz about Python - Part 7following the previous test set, part 7 continues with the topic built-in functions in python. let's try with quantrimang to try the 10 questions below.
- Zip () function in Pythonthe zip () function in python returns a zip object, a list iterator of tuples that combines elements from other iterators (made of iterable words).
- Function sleep () in Pythonmodule time in python provides some very useful functions to handle time-related tasks. one of the most commonly used functions is sleep ().
- Decorator in Pythondecorator is used a lot in python. so how to create a decorator and why you should use it. let's go find the answer!
- Multiple choice quiz about Python - Part 6to help readers add to their knowledge of python's built-in functions, the network administrator will send you multiple choice questions on this topic. please try.
- Classmethod () function in Pythonin python, the classmethod () function returns a class method for the function. how is the syntax of classmethod () function, what parameters does it have and how to use it? invites you to read the track.
- Multiple Inheritance in Pythoninheritance allows us to declare the new class to re-use the parent class's functions and attributes and extra functions. in this article, quantrimang will continue the lesson with the theme inheritance but at a deeper level, which is the inheritance and the order of method access of the parent classes (method resolution order).
- The map () function in Pythoncontinuing with the topic of built-in functions in python, the article will introduce you to the map () function with syntax, usage as well as specific examples. invites you to read the track.