You might wonder⦠why not just write your code directly in the file? Why bother putting everything inside a function called main()?
β The answer: It makes your code easier to read, organize, and reuse!
Let's say you're writing a Dungeons & Dragons adventure setup, and you just start writing code like this.
π― This works fine! But what if we wanted to expand this game later? What if we wanted to reuse some parts or control when things run? π€
Now, let's organize the same game using a main() function:
β Why is this better?
Easier to Read β Instead of a wall of code, you can now see the main logic at a glance.
Reusability β Now we can use roll_dice() anywhere without rewriting the code.
Organization β Each function does one specific job, making debugging easier.
Python starts at the bottom, sees main(), and jumps up to execute it.
If we didn't call main(), nothing would happen!
β This is called the dunder main call __name__ == "__main__"
it helps control when and how your program runs.
dunder means DOUBLE UNDERLINE
If we run adventure.py directly, the program sees if __name__ == "__main__": as True, so it calls main().
If we import adventure.py into another file, __name__ is NOT "__main__", so main() does NOT run automatically.
Every Python file has a special built-in variable called __name__.
When a file is run directly, Python sets __name__ = "__main__".
When a file is imported into another file, Python sets __name__ = "filename".
What if we want to use roll_dice() in a new game file called battle.py?
We Import The File, without issue, BUT...
When it imports the file, it reads it from top to bottom, so if we see main called, it will call main anywhere it sees it!!
1οΈβ£ Create a weapons.py file with a function that returns a random weapon.
2οΈβ£ Add a main() function that prints a battle message.
3οΈβ£ Use if __name__ == "__main__": to control when main() runs.
4οΈβ£ Import weapons.py into another file and make sure only the function runs, NOT the battle message!
Here's An Example To Help You Start!!