Python Main Method Tries to Run My Main Method Over and Over Again

Python is 1 of the nearly popular programming languages to larn. The main function in Python acts equally the point of execution for whatever program. Defining the master function in Python programming is a necessity to start the execution of the program equally it gets executed only when the programme is run straight and not executed when imported every bit a module.

To sympathise more nigh python main function, permit's have a look at the topics that I will exist covering in this article:

  • What is Python functions?
  • What is main role in Python
  • A Basic Python master()
  • Python Execution modes

Let's get started.

What is Python functions?

A function is a block of reusable lawmaking that forms the foundation of performing actions in a programming language. They are leveraged to perform computations on the input data and present the output to the end user.

We accept already learned that a role is a piece of lawmaking written to perform a specific task. There are 3 types of functions in Python namely Built-in function, user-defined functions, and anonymous functions. Now, the chief function is similar whatsoever other function in Python.

So let's sympathise what exactly is the main role in Python.

What is Primary Function in Python

In nigh programming languages, at that place is a special part which is executed automatically every time the program is run. This is cipher but the principal function, or main() as it is usually denoted. Information technology substantially serves as a starting signal for the execution of a plan.

In Python, it is non necessary to define the main office every time you lot write a program. This is considering the Python interpreter executes from the top of the file unless a specific part is defined. Hence, having a defined starting bespeak for the execution of your Python program is useful to better sympathize how your program works.

A Basic Python main()

In well-nigh Python programs/scripts, yous might see a part definition, followed by a conditional statement that looks like the example shown below:

def main():     impress("Hello, World!")     if __name__== "__main__" : main()

Notice out our Python Preparation in Elevation Cities/Countries

India U.s.a. Other Cities/Countries
Bangalore New York U.k.
Hyderabad Chicago London
Delhi Atlanta Canada
Chennai Houston Toronto
Bombay Los Angeles Australia
Pune Boston UAE
Kolkata Miami Dubai
Ahmedabad San Francisco Philippines

Does Python need a Master Part?

Information technology is not a compulsion to have a a Main Part in Python, however, In the above instance, you lot tin see, there is a role called 'main()'. This is followed by a conditional 'if' statement that checks the value of __name__, and compares it to the string "__main__". On evaluation to True, information technology executes main().

And on execution, it prints "Hello, World!".

This kind of code pattern is very mutual when you lot are dealing with files that are to be executed every bit Python scripts, and/or to be imported in other modules.

Let'due south understand how this code executes. Before that, it's very necessary to sympathise that the Python interpreter sets __name__ depending on the way how the code is executed. And then, let's learn about the execution modes in Python

Python Execution Modes

There are two main ways by which you tin tell the Python interpreter to execute the code:

  • The near common way is to execute the file as a Python Script.
  • By importing the necessary code from ane Python file to another.

Whatsoever the manner of execution you choose, Python defines a special variable chosen __name__, that contains a string. And as I said before, the value of this string depends on how the code is beingness executed.

Sometimes, when you are importing from a module, you would like to know whether a item module'southward function is being used as an import, or if you are just using the original .py (Python script) file of that module.

To assist with this, Python has a special built-in variable, called __name__. This variable gets assigned the string "__main__" depending on how you are running or executing the script.

What is __main__ in Python?

Python Main Function is the beginning of whatever Python program. When we run a program, the interpreter runs the lawmaking sequentially and volition non run the master function if imported as a module, simply the Chief Function gets executed only when it is run as a Python program.

So, if y'all are running the script straight, Python is going to assign "__main__" to __name__, i.e., __name__= "__main__". (This happens in the groundwork).

Equally a upshot, you end up writing the conditional if statement as follows:

if __name__ == "__main__" : 		Logic Statements

Hence, if the conditional statement evaluates to Truthful, it means, the .py (Python Script) file is being run or executed directly.

Information technology is of import to understand that, if you lot are running something directly on the Python beat out or last, this provisional statement, by default, happens to be True.

As a result, programmers write all the necessary functional definitions on the height, and finally write this statement at the end, to organize the code.

In short, __name__ variable helps you to check if the file is beingness run directly or if it has been imported.

In that location are a few things you lot should keep in mind while writing programs that are going to take the main function. I take listed them in iv elementary steps. Y'all tin consider this equally a skillful nomenclature to follow while writing Python programs that accept the main function in them.

  • Use functions and classes wherever possible.

We take been learning the concepts of Object Oriented Programming and their advantages for a long time. It is absolutely necessary to identify bulk logic codes in meaty functions or classes. Why? For amend lawmaking reusability, better understanding and for overall code optimization. In this style, you can control the execution of the code, rather than letting the Python interpreter execute it as before long as it imports the module.

Let us come across the following slice of code:

def get_got(): print("…Fetching GOT Data… n") data="Bran Stark wins the Fe Throne. north" print("…GOT Data has been fetched…northward") return information  print("due north Demo: Using Functions n") got=get_got() impress(got)        

In the above example, I've defined a function called "get_got", which returns the string stored in the variable "information". This is and so stored in the variable called "got" which is then printed. I accept written downward the output beneath:

program2-Understanding main function in python 3-Edureka

  • Utilize __name__ to control the execution of your code.

At present you lot know what __name__ variable is, how and why it is used. Let united states expect at the lawmaking snippet below:

At present you know what __name__ variable is, how and why it is used. Let us expect at the code snippet below:

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

In the above example, the conditional if statement is going to compare the values of the variable __name__ with the string "__main__". If, and simply if it evaluates to Truthful, the next set up of logical statements are executed. Since nosotros are directly running the program, we know that the conditional statement is going to be True. Therefore, the statements are executed, and we become the desired output. In this way, we can use the __name__ variable to control the execution of your lawmaking. Y'all may refer to the output displayed below:

program6-Understanding main function in python 3-Edureka

  • Create a function main() which has the code to be run.

By now, you know the various means how a Python lawmaking can be executed. You also know why and when a principal() function is used. Information technology is time to apply it. Look at the post-obit piece of code:

print("n Main Function Demo n") 	def demo(got): 		print("…Beginning Game Of Thrones…n") 		new_got = str.split(got) 		impress("…Game of Thrones has finished…n") 		render new_got 	def main(): 		got= "n Bran Stark wins the Atomic number 26 Throne northward" 		print(got) 		new_got = demo(got) 		print(new_got) 	if __name__ == "__main__": 		principal()        

In the above example, I have used the definition of main(), which contains the program logic I want to run. I've likewise divers a function called 'demo', to include a piece of code, that can exist reused every bit and when necessary. Furthermore, I have inverse the conditional cake, such that, it executes main().

In this style, I put the lawmaking I want to run within master(), the programming logic in a function called 'demo' and called main() inside the conditional block. I have assimilated the output of the lawmaking and written it downwardly below for your piece of cake reference:

program3-Understanding main function in python 3-Edureka

Note: If you run this code every bit a script or if y'all import information technology, the output is going to be the same. You may look at the output below:

  • Call other functions from chief().

When yous write total-fledged Python programs, there could be numerous functions that could exist called and used. By and large, some functions should be chosen as soon as the execution of the program starts. Hence, it is always good to phone call other functions from the main() itself.

Let united states look at beneath lawmaking fragment:

print("n Chief Function Demo n") 	def demo(got): 		print("…Beginning Game Of Thrones Demo1…n") 		new_got = str.split(got) 		print("…Game of Thrones has finished…due north") 		render new_got 	def getgot(): 		impress("…Getting GOT Data…n") 		got="Bran Stark wins the Iron Throne n" 		print("…GOT Data has been returned…north") 		return got 	def main(): 		got= getgot() 		print(got) 		new_got = demo(got) 		print(new_got) 	if __name__ == "__main__": 		main()        

In the above example, I accept defined a function called "getgot()" to fetch the data. And this function is called from inside the main() itself.

Hence, information technology is always good to call other functions from within the main() to compose your unabridged task from smaller sub-tasks, that can execute independently. I have also shared the output of the in a higher place code in the section below:

program5-Understanding main function in python 3-Edureka

I hope yous were able to get through this article and get a off-white agreement of what the chief() office in Python is all about, and how it tin be used. With the aid of main() office in Python, we can execute a ton of functionalities as and when needed, and also command the menstruum of execution.

If you plant this article on "Understanding Main Function in Python" relevant, cheque out the Edureka's Python Certification Training, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. This training helps learners gain expertise in scripting in Python and ready individuals to take up Python job opportunities.

Got a question for the states? Please mention it in the comments section of "Main Function In Python" blog and we will get dorsum to you at the earliest or join Python Chief course.

To get in-depth knowledge on Python Programming linguistic communication along with its diverse applications, you can enroll hither for alive online grooming with 24/vii support and lifetime access.

hicksworde1948.blogspot.com

Source: https://www.edureka.co/blog/python-main-function/

0 Response to "Python Main Method Tries to Run My Main Method Over and Over Again"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel