Arguments in the main() Function in Python
At the end of this tutorial, we should have learned whether or not it is good practice to have arguments inside main()
.
Python main()
Function
In Python, the main()
function is primarily applicable when we want to execute a function. To execute that function, we first need to define the function, which is where we will need to define the main()
function.
In situations like this, however, the main()
function is mainly a naming convention, such that we can switch the main
with another name, and the function will execute just fine.
Look at the example image below where we have defined the main()
function:
You will see that in the second image, we switched the main
name to alpha
, and we can see that the function executes just fine.
Arguments in the main()
Function in Python
Having arguments inside the main()
function is not a bad practice. It is a question of why you must have arguments inside the main()
function.
In the image below, we have declared a variable, and it prints the results:
We can also declare the same variable using the main()
function, as seen in the image below, giving us the same result.
So, we can see here that the first instance is easier to grasp and a better way to write the code because it is briefer. It shows we can declare a simple variable without the need to define main()
.
However, when we want to import a function into another function, we will need first to define a function.
Let us create two files inside our Python folder, name the first file main.py
and the second file new.py
. Inside the main.py
file, add these snippets:
Code Snippet- main.py
:
def main(a):
print(f"look at this {a}")
print("do you see?")
Then in the new.py
file, we will import main.py
, add a bit more code and execute both.
Code Snippet- new.py
:
import main
print("this is new")
main
When we execute the new.py
, it also executes the function from main.py
.
Conclusion
So far, we can deduce that having arguments inside the main()
function is not a question of good or bad practice; it’s a case of application. Some snippets are straightforward, and we don’t need to include functions, but there are instances where we need functions and having arguments inside these functions is never a bad practice.
Fisayo is a tech expert and enthusiast who loves to solve problems, seek new challenges and aim to spread the knowledge of what she has learned across the globe.
LinkedIn