Python Hoofdfunctie en -methode: Begrijp def Main()
โก Slimme samenvatting
Python main function marks the starting point where the interpreter begins running a program. Defined with def main() and paired with the if __name__ == โ__main__โ guard, it separates reusable module code from standalone script execution.

Wat is Python Hoofdfunctie?
De Python hoofdfunctie is the starting point of any program. When the program is run, the Python interpreter runs the code sequentially. The main function is executed only when it is run as a Python program. It will not run the main function if it is imported as a module.
Wat is de functie def main()? Python? To understand this, consider the following example code, which is part of the core Python programmering basisprincipes:
def main() Voorbeeld 1
def main():
print ("Hello World!")
print ("Guru99")
Hier zien we twee afdrukken: de ene is gedefinieerd binnen de hoofdfunctie en luidt "Hello World!", de andere is onafhankelijk en luidt "Guru99โ. Wanneer je de functie def main() uitvoert:
- Enkel en alleen "Guru99โ print uit
- en niet de code โHallo wereld!โ
Het is omdat we de oproep niet hebben gemeld functie โif__name__== โ__main__โ.
Het is belangrijk dat u na het definiรซren van de hoofdfunctie de code aanroept met if__name__== โ__main__โ en vervolgens de code uitvoert. Alleen dan krijgt u de uitvoer โhello world!โ in de programmeerconsole. Bekijk de volgende code
def main() Voorbeeld 2
def main():
print("Hello World!")
if __name__ == "__main__":
main()
print("Guru99")
GuruIn dit geval staat er 99 afgedrukt.
Hier is de uitleg,
- . Python interpreter een bronbestand leest, zal het alle daarin gevonden code uitvoeren.
- . Python voert het โbronbestandโ uit als het hoofdprogramma, het stelt de speciale variabele (__name__) in op een waarde (โ__main__โ).
- Wanneer u de hoofdfunctie in Python uitvoert, leest deze de โifโ -instructie en controleert of __name__ gelijk is aan __main__.
- In Python โif__naam__== โ__main__โ stelt u in staat om de Python bestanden ofwel als herbruikbare modules of zelfstandige programma's.
Why Use a main() Function in Python?
Python does not force you to write a main function, yet experienced developers use one in almost every non-trivial script. The def main() pattern brings order to a file and makes the code safe to reuse. Here are the main reasons to use it:
- Clear entry point: A main() function tells any reader exactly where the program starts, so the logic is easy to follow.
- Herbruikbare modules: Code guarded by if __name__ == โ__main__โ runs only on direct execution, so other files can import your functions without side effects.
- Local scope: Variables created inside main() stay local, which avoids accidental clashes with global names elsewhere in the module.
- Easier testing: Isolating logic in main() lets a test suite call it directly and check the result.
- Shared convention: A main() function is a widely recognized signal of the program entry point, which improves maintainability across teams.
In short, a main() function is optional in Python, but it keeps larger programs readable, testable, and safe to import.
De __name__ variabele en Python Module
Om het belang van de variabele __name__ te begrijpen in Python hoofdfunctiemethode, overweeg de volgende code:
def main():
print("hello world!")
if __name__ == "__main__":
main()
print("Guru99")
print("Value in built variable name is: ",__name__)
Bedenk nu dat code als een module wordt geรฏmporteerd
import MainFunction
print("done")
Hier is de code-uitleg: Zoals C, Python gebruikt == voor vergelijking terwijl = voor toewijzing. Python interpreter gebruikt de hoofdfunctie op twee manieren
directe vlucht:
- __naam__=__hoofd__
- if statement == True, en het script in _main_zal worden uitgevoerd
importeren als module
- __name__= bestandsnaam van de module
- if statement == false, en het script in __main__ zal niet worden uitgevoerd
Wanneer de code wordt uitgevoerd, wordt gecontroleerd op de modulenaam met 'if'. Dit mechanisme zorgt ervoor dat de hoofdfunctie alleen wordt uitgevoerd als directe uitvoering en niet wanneer deze als module wordt geรฏmporteerd.
Bovenstaande voorbeelden zijn Python 3 codes, als je wilt gebruiken Python 2. Houd rekening met de volgende code
def main(): print "Hello World!" if __name__== "__main__": main() print "Guru99"
In Python 3, je hoeft if__name niet te gebruiken. De volgende code werkt ook
def main():
print("Hello World!")
main()
print("Guru99")
Let op: Zorg ervoor dat u na het definiรซren van de hoofdfunctie een beetje inspringing laat staan โโen dat u de code niet direct onder de def main(): functie declareert, anders krijgt u een inspringfout.
How to Pass Command-Line Arguments to the Python main() Function
A main() function is the natural place to handle input that a user passes on the command line. Python stores these values in the sys.argv list, which the standard sys module provides. The first item, sys.argv[0], is the script name, and every value after it is an argument supplied by the user.
The following example reads and prints command-line arguments from inside a main() function:
import sys def main(): print("Script name:", sys.argv[0]) print("Arguments passed:", sys.argv[1:]) if __name__ == "__main__": main()
If you save the file as script.py and run python script.py alpha beta, the program prints the script name and the list [โalphaโ, โbetaโ]. Because the values arrive inside main(), the logic stays organized and easy to test.
Here are a few practical tips when working with command-line input:
- Slice off the script name: Use sys.argv[1:] to read only the arguments the user typed.
- Use argparse for real tools: The built-in argparse module parses flags, options, and help text far more safely than reading sys.argv by hand.
- Return an exit code: Wrap the call as sys.exit(main()) so the return value of main() becomes the process exit status.
- Validate early: Check the number and type of arguments at the top of main() before running the rest of the program.
This pattern turns a simple script into a reliable command-line tool while keeping every step inside a single, testable main() function.
Python main() Function vs Other Programming Languages
Developers coming from C, C++of Java often expect a mandatory main() function. Python works differently because it is an interpreted language, so the interpreter simply runs a file from the top line to the bottom. The main() function in Python is therefore a convention rather than a rule.
- C, C++, C# en Java: A main() function is a required entry point. The runtime automatically calls it, and there can be only one per program.
- Python: No main() function is required. Execution starts at the first line of the file, and def main() runs only if your code calls it.
- The guard: The if __name__ == โ__main__โ block gives Python a purpose similar to a compiled main() by marking code that should run only when the file is the main program.
So while other languages enforce a main() entry point, Python leaves the choice to you, offering the same clarity through convention instead of a compiler rule.




