Table of Contents
What is a Python function
What is the main function in Python
A basic Python main()
Python execution modes
What is __main__ in Python
Home Backend Development Python Tutorial Learning Python, don't you still know the main function?

Learning Python, don't you still know the main function?

Apr 12, 2023 pm 02:58 PM
programming function language

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:

  • What is the Python function
  • The main function in Python What is the function
  • What does a basic Python main() look like
  • Python execution mode

Let's get started

What is a Python function

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.

What is the main function in Python

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.

A basic Python main()

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()
Copy after login

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

Python execution modes

There are two main ways to tell the Python interpreter to execute code:

  • The most common The method is to execute the file as a Python script
  • By importing the necessary code from one Python file to another

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.

What is __main__ in Python

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
Copy after login

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)
Copy after login

在上面的示例中,我定义了一个名为 get_got 的函数,它返回存储在变量 data 中的字符串。然后将其存储在名为 got 的变量中,最后打印该变量。

输出如下:

Learning Python, dont you still know the main function?

使用 __name__ 来控制代码的执行

现在我们知道了什么是 __name__ 变量,那么该如何以及为什么使用它。让我们看看下面的代码片段:

if __name__ == "__main__":
got = "Game of Thrones is a legendary shown"
print(got)
new_got = str.split(got)
print(new_got)
Copy after login

在上面的示例中,条件 if 语句将比较变量 __name__ 的值与字符串 __main__。当且仅当它的计算结果为 True 时,才会执行下一组逻辑语句。由于我们直接运行程序,我们知道条件语句将是 True。因此语句被执行,我们得到了想要的输出。这样我们就可以使用 __name__ 变量来控制我们代码的执行。

输出如下:

Learning Python, dont you still know the main function?

创建一个包含要运行代码的函数 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()
Copy after login

在上面的例子中,我们使用了 main() 的定义,它包含了我们要运行的程序逻辑。我们还定义了一个名为 demo 的函数,包含一段代码,可以在必要时复用。此外我们还更改了条件块,使其执行 main()。

这样,我们将要运行的代码放在 main() 中,将编程逻辑放在一个名为 demo 的函数中,并在条件块中调用 main()。

来看一下输出:

Learning Python, dont you still know the main function?

可以尝试一下,如果将此代码作为脚本运行或导入它,则输出将是相同的。

从 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()
Copy after login

在上面的示例中,我们定义了一个名为 getgot() 的函数来获取数据,这个函数是从 main() 本身调用的。

因此,从 main() 中调用其他函数以将整个任务从可以独立执行的较小子任务中组合起来总是较好的选择。

输出如下:

Learning Python, dont you still know the main function?

希望通过这篇文章,对于 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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Complete collection of excel function formulas Complete collection of excel function formulas May 07, 2024 pm 12:04 PM

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

C++ Function Exception Advanced: Customized Error Handling C++ Function Exception Advanced: Customized Error Handling May 01, 2024 pm 06:39 PM

Exception handling in C++ can be enhanced through custom exception classes that provide specific error messages, contextual information, and perform custom actions based on the error type. Define an exception class inherited from std::exception to provide specific error information. Use the throw keyword to throw a custom exception. Use dynamic_cast in a try-catch block to convert the caught exception to a custom exception type. In the actual case, the open_file function throws a FileNotFoundException exception. Catching and handling the exception can provide a more specific error message.

The Mistral open source code model takes the throne! Codestral is crazy about training in over 80 languages, and domestic Tongyi developers are asking to participate! The Mistral open source code model takes the throne! Codestral is crazy about training in over 80 languages, and domestic Tongyi developers are asking to participate! Jun 08, 2024 pm 09:55 PM

Produced by 51CTO technology stack (WeChat ID: blog51cto) Mistral released its first code model Codestral-22B! What’s crazy about this model is not only that it’s trained on over 80 programming languages, including Swift, etc. that many code models ignore. Their speeds are not exactly the same. It is required to write a "publish/subscribe" system using Go language. The GPT-4o here is being output, and Codestral is handing in the paper so fast that it’s hard to see! Since the model has just been launched, it has not yet been publicly tested. But according to the person in charge of Mistral, Codestral is currently the best-performing open source code model. Friends who are interested in the picture can move to: - Hug the face: https

Things to note when Golang functions receive map parameters Things to note when Golang functions receive map parameters Jun 04, 2024 am 10:31 AM

When passing a map to a function in Go, a copy will be created by default, and modifications to the copy will not affect the original map. If you need to modify the original map, you can pass it through a pointer. Empty maps need to be handled with care, because they are technically nil pointers, and passing an empty map to a function that expects a non-empty map will cause an error.

Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Oct 11, 2024 pm 08:58 PM

Pythonempowersbeginnersinproblem-solving.Itsuser-friendlysyntax,extensivelibrary,andfeaturessuchasvariables,conditionalstatements,andloopsenableefficientcodedevelopment.Frommanagingdatatocontrollingprogramflowandperformingrepetitivetasks,Pythonprovid

Unleash Your Inner Programmer: C for Absolute Beginners Unleash Your Inner Programmer: C for Absolute Beginners Oct 11, 2024 pm 03:50 PM

C is an ideal language for beginners to learn programming, and its advantages include efficiency, versatility, and portability. Learning C language requires: Installing a C compiler (such as MinGW or Cygwin) Understanding variables, data types, conditional statements and loop statements Writing the first program containing the main function and printf() function Practicing through practical cases (such as calculating averages) C language knowledge

Collection of C++ programming puzzles: stimulate thinking and improve programming skills Collection of C++ programming puzzles: stimulate thinking and improve programming skills Jun 01, 2024 pm 10:26 PM

C++ programming puzzles cover algorithm and data structure concepts such as Fibonacci sequence, factorial, Hamming distance, maximum and minimum values ​​of arrays, etc. By solving these puzzles, you can consolidate C++ knowledge and improve algorithm understanding and programming skills.

The Key to Coding: Unlocking the Power of Python for Beginners The Key to Coding: Unlocking the Power of Python for Beginners Oct 11, 2024 pm 12:17 PM

Python is an ideal programming introduction language for beginners through its ease of learning and powerful features. Its basics include: Variables: used to store data (numbers, strings, lists, etc.). Data type: Defines the type of data in the variable (integer, floating point, etc.). Operators: used for mathematical operations and comparisons. Control flow: Control the flow of code execution (conditional statements, loops).

See all articles