Home > Article > Backend Development > Learning Python, don’t you still know the main function?
The main function in Python serves as the execution point of the program. Defining the main function in Python programming is a necessary condition to start the program execution, but it is only executed when the program is directly run, and will not be executed when imported as a module.
To learn more about the Python main function, we will learn step by step from the following points:
Let's get started
I believe many friends are familiar with functions. Functions are reusable blocks of code, which form the basis for performing operations in programming languages. They are used to perform calculations on input data and output presented to the end user.
We have learned that a function is a piece of code written to perform a specific task. Functions in Python are divided into three types, namely built-in functions, user-defined functions and anonymous functions. At the same time, we need to make it clear that the main function is the same as any other function in Python, there is no difference.
So let us understand what the main function in Python is.
In most programming languages, there is a special function that is automatically executed every time the program runs. This is the main function, or usually Represents main(), which is essentially the starting point of program execution.
In Python, it is not necessary to define the main function every time you write a program. This is because the Python interpreter will execute from the top of the file unless a specific function is defined. Therefore, defining a starting point for the execution of a Python program helps to better understand how the program works.
In most Python programs/scripts, we may see a function definition followed by a conditional statement, like this:
def main(): print("Hello, World!") if __name__== "__main__" : main()
Is the main function necessary for Python?
It is not mandatory to have the main function in Python. However, in the above example, we can see that a function named The function of main(), below is a conditional if statement, which checks the value of __name__ and compares it with the string __main__. When it is True, main() will be executed.
When executed, "Hello, World!" will be printed.
This code pattern is very common when we are dealing with files to be executed as Python scripts or to be imported in other modules.
Let's take a closer look at how this code is executed. First, it is very necessary for us to understand that the Python interpreter setting __name__ depends on how the code is executed. So, let’s learn about execution modes in Python
There are two main ways to tell the Python interpreter to execute code:
No matter which execution mode we choose, Python will define a A special variable named __name__ that contains a string. As we saw earlier, the value of this string depends on how the code is executed.
Sometimes when we import from a module, we want to know if a function of a particular module is used as an import, or if just the original .py (Python script) file of that module is used.
To solve this problem, Python has a special built-in variable called __name__, which can be assigned the string __main__ depending on how the script is run or executed.
Python main function is the entrance to any Python program. When we run the program, the interpreter runs the code sequentially. If imported as a module, the main function will not be run. The main function will only be executed when run as a Python program.
So if we run the script directly, Python will assign __main__ to __name__, that is, __name__="__main__".
So, if the conditional statement evaluates to True, it means that the .py (Python script) file is being run or executed directly.
One important thing to note is that if we run something directly in the Python shell or terminal, this conditional statement happens to be True by default.
In the end, we habitually wrote all necessary function definitions at the top of the code file, and finally wrote this statement at the end of the file to organize the code.
if __name__ == "__main__" : Logic Statements
In short, the __name__ variable can help us check whether the file is run directly or imported.
When writing a program with main function, we need to remember the following things
Use functions and classes as much as possible
长期以来,我们一直在学习面向对象编程的概念及其优势,所以绝对有必要将批量逻辑代码放在紧凑的函数或类中。通过这种方式,我们可以控制代码的执行,而不是让 Python 解释器一导入模块就执行它。
让我们看看下面的一段代码:
def get_got(): print("…Fetching GOT Data… n") data="Bran Stark wins the Iron Throne. n" print("…GOT Data has been fetched…n") return data print("n Demo: Using Functions n") got=get_got() print(got)
在上面的示例中,我定义了一个名为 get_got 的函数,它返回存储在变量 data 中的字符串。然后将其存储在名为 got 的变量中,最后打印该变量。
输出如下:
使用 __name__ 来控制代码的执行
现在我们知道了什么是 __name__ 变量,那么该如何以及为什么使用它。让我们看看下面的代码片段:
if __name__ == "__main__": got = "Game of Thrones is a legendary shown" print(got) new_got = str.split(got) print(new_got)
在上面的示例中,条件 if 语句将比较变量 __name__ 的值与字符串 __main__。当且仅当它的计算结果为 True 时,才会执行下一组逻辑语句。由于我们直接运行程序,我们知道条件语句将是 True。因此语句被执行,我们得到了想要的输出。这样我们就可以使用 __name__ 变量来控制我们代码的执行。
输出如下:
创建一个包含要运行代码的函数 main()。
到目前为止,我们已经了解了 Python 代码的各种执行方式,同时我们还知道为什么以及何时使用 main() 函数,下面就来应用它。看下面这段代码:
print("n Main Function Demo n") def demo(got): print("…Beginning Game Of Thrones…n") new_got = str.split(got) print("…Game of Thrones has finished…n") return new_got def main(): got= "n Bran Stark wins the Iron Throne n" print(got) new_got = demo(got) print(new_got) if __name__ == "__main__": main()
在上面的例子中,我们使用了 main() 的定义,它包含了我们要运行的程序逻辑。我们还定义了一个名为 demo 的函数,包含一段代码,可以在必要时复用。此外我们还更改了条件块,使其执行 main()。
这样,我们将要运行的代码放在 main() 中,将编程逻辑放在一个名为 demo 的函数中,并在条件块中调用 main()。
来看一下输出:
可以尝试一下,如果将此代码作为脚本运行或导入它,则输出将是相同的。
从 main() 调用其他函数
当我们编写成熟的 Python 程序时,可能有许多可以调用和使用的函数。通常情况下,一些函数应该在程序开始执行时立即调用。因此,从 main() 本身调用其他函数就是最佳的选择了。
让我们看看下面的代码片段:
print("n Main Function Demo n") def demo(got): print("…Beginning Game Of Thrones Demo1…n") new_got = str.split(got) print("…Game of Thrones has finished…n") return new_got def getgot(): print("…Getting GOT Data…n") got="Bran Stark wins the Iron Throne n" print("…GOT Data has been returned…n") return got def main(): got= getgot() print(got) new_got = demo(got) print(new_got) if __name__ == "__main__": main()
在上面的示例中,我们定义了一个名为 getgot() 的函数来获取数据,这个函数是从 main() 本身调用的。
因此,从 main() 中调用其他函数以将整个任务从可以独立执行的较小子任务中组合起来总是较好的选择。
输出如下:
希望通过这篇文章,对于 Python 中 main() 函数的全部内容以及如何使用它有一个全面而正确的理解。借助 Python 中的 main() 函数,我们可以在需要时执行大量功能,还可以控制执行流程。
The above is the detailed content of Learning Python, don’t you still know the main function?. For more information, please follow other related articles on the PHP Chinese website!