-2

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()
bob george
  • 95
  • 2
  • 9
  • What is the specific issue that you're having with creating a main() function? If you just need a main() function for your script, just write a function named `main()` and call it by placing `if __name__ == '__main__': main()` at the bottom of your code. – AdmiralWen Apr 26 '15 at 20:30
  • @AdmiralWen I tried that and it says name is not defined – bob george Apr 26 '15 at 20:32
  • Sounds like you might have a problem elsewhere in your code. Can you post the exact code for which you "tried" writing the main() function and got the name error? – AdmiralWen Apr 26 '15 at 20:38
  • @AdmiralWen I updated my code to show you what ive entered. – bob george Apr 26 '15 at 20:46
  • 1
    Well, first you need to define `main()`, which I'm assuming you know? Currently your code is trying to call main() but it isn't defined, so you'll get a NameError. Secondly, both "name" and "main" is spelled with double underscores: `__name__`, not `_name_`. – AdmiralWen Apr 27 '15 at 03:54

1 Answers1

2
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

Community
  • 1
  • 1
Tom
  • 918
  • 6
  • 19