开发者

Main functions, pythonic?

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开发者_Go百科 Input")

Any help/pointers would be appreciated?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜