Search code examples
pythonfunctioninputmoduleprogram-entry-point

How to I make my program a main function?


I would like my program to have a main function so I can run it as a module or main program. Main functions are new to me and I have no idea how to do this.

#!/usr/bin/python3

def main():
#left dashboard
    ld = raw_input("Left dashboard switch (0 or 1): ")

#right dashboard
    rd = raw_input("Right dasboard switch (0 or 1): ")

#child lock
    cl = raw_input("Child lock switch (0 or 1): ")

#master lock
    ml = raw_input("Master unlock switch (0 or 1): ")

#left inside
    li = raw_input("Left inside handle (0 or 1): ")

#left outside
    lo = raw_input("Left outside handle (0 or 1): ")

#right inside
    ri = raw_input("Right inside handle (0 or 1): ")

#right outside
    ro = raw_input("Right outside handle (0 or 1): ")

#gear shift
    gs = raw_input("Gear shift position (P, N, D , 1 ,2 ,3 or R): ")

    d = 0
    r = 0
    l = 0
    if gs == "P" and ml == "1" and cl == "0":
            d = 1
    if ri == "1" or ro == "1" or rd == "1":
            r = 1
    if li == "1" or lo == "1" or ld == "1":
            l = 1
    if d == 0:
            print "Both doors closed"
if _name_ == "_main_":
    main()

Solution

  • def main():
        #code here
    
    if __name__ == '__main__': main()
    

    all your code needs to be encased in the main function. The function is them called at the bottom python docs - __main__. More info on main here