I am just getting into Python coding and I'm wondering which is considered more pythonic? Example A: An obvious main method.
#!/usr/bin/env python -tt
import random
def dice_roll(num=1):
for _ in range(num):
print("Rolled a", random.randrange(1,7,1))
def main()
random.seed()
try:
num = int(input("How many dice? "))
dice_roll(num)
except ValueError:
print("Non-numeric Input")
if __name__ == '__main__':
main()
or Example B: No main method.
#!/usr/bin/env python -tt
import random
def dice_roll(num=1):
for _ in range(num):
print("Rolled a", random.randrange(1,7,1))
if __name__ == '__main__':
random.seed()
try:
num = int(input("How many dice? "))
dice_roll(num)
except ValueError:
print("Non-numeric Input")
Any help/pointers would be appreciated?
There are three types of functions in Python namely Built-in function, user-defined functions, and anonymous functions.
__main__ is the name of the environment where top-level code is run. “Top-level code” is the first user-specified Python module that starts running. It's “top-level” because it imports all other modules that the program needs. Sometimes “top-level code” is called an entry point to the application.
There are three functions in python that provide vast practicality and usefulness when programming. These three functions, which provide a functional programming style within the object-oriented python language, are the map(), filter(), and reduce() functions.
For python main function, we have to define a function and then use if __name__ == '__main__' condition to execute this function. If the python source file is imported as module, python interpreter sets the __name__ value to module name, so the if condition will return false and main method will not be executed.
A is better because it allows you to import your module and execute the stuff in main
without having to funk about with things unnecessarily. In fact, that might be a good reason to name it something better than main
if it really represents an actual function of your module.
Well, when it comes to being Pythonic, I'd say both are equally Pythonic, because that refers to specific programming conventions, and doesn't (and shouldn't) govern the way you code.
However, people usually, use the first form, as it's easier to import
and invoke the script from another one, then.
I would say example A is more Pythonic but they are both acceptable. Mainly because you can import main, but usually you would not need to do so.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With