[Tutor] Main function

Danny Yoo dyoo at hashcollision.org
Tue May 20 21:28:00 CEST 2014


> Since I'm new to python and don't really know how to write programs yet, my
> first question would be what exactly is the main function, because we did a
> similar assignment before this one that included it, and I'm not sure what
> exactly it does.


When you write a program, you write a collection of function and
variable definitions.  But they don't have to be in too particular of
an order.  For example, we might have something like

#########################
def f(x): return x * x
def g(x): return x**0.5
def h(a, b): return g(f(a) + f(b))
#########################

But nothing stops us from writing the definitions in a different order:

#########################
def h(a, b): return g(f(a) + f(b))
def g(x): return x**0.5
def f(x): return x * x
#########################


However, it does leave the question of: how do you start a program,
and from where do things begin?


In most programming languages, you choose a particular function and
designate it as the "main" entry point into your program.

#########################
def h(a, b): return g(f(a) + f(b))

def g(x): return x**0.5

def f(x): return x * x

def main():
    print("The hypotenuse is: %d" % h(3, 4))
#########################

In Python, you don't have to call it "main", but in several other
languages, you do.


There's one more piece you add to the bottom of the program to start
things going, a snippet that looks like this:

    if __name__ == '__main__':
        main()

This is a purely Python issue.  It says that if the file is being run
as the main program (in which case, the __name__ is '__main__'), then
kick things off by calling the main function.  You put this at the
bottom of your program.



#########################
def h(a, b): return g(f(a) + f(b))

def g(x): return x**0.5

def f(x): return x * x

def main():
    print("The hypotenuse is: %d" % h(3, 4))

if __name__ == '__main__':
    main()
#########################


See:

    http://effbot.org/pyfaq/tutor-what-is-if-name-main-for.htm


More information about the Tutor mailing list