Skip navigation

Running code in python may seem a bit tricky at first…

I now understand the reason that everyone seems to use the if __name__ == ‘__main__’ HACK (and yes, it is a hack, generally when you see use of double underscored surrounded __something__ that’s accessing an internal attribute, and generally in my opinion at this point, that kind of thing __shouldn’t__ be required.)

But anyway, I’ll show you how to write a simple python program (assuming you know the general syntax) so you don’t end up with some weird spaghetti, .

Exploring what works and what doesn’t


print 'testing my script'

#f1()  # does not work here, the interpretter
         # has not "seen" the def for f1() yet
#f2()  # does not work here, f2() unseen as yet

def f1():
  print 'f1 is running'
  
f1()  # works
#f2()  # will not work here, f2 not def yet
  
def f2():
  print 'f2 is running'
    
f1()  # works, f1 has been def'd
f2()  # works, f2 has been def'd

The “right way”

print 'testing my script'

##
# begin function defs
# just put all functions up here, together
def Main():    
  f1()  # works
  f2()  # works

def f1():
  print 'f1 is running'
  
def f2():
  print 'f2 is running'
#
# end function defs
##

# just execute main now.
# because the interpretter will have "seen"
# ALL the functions that Main() references at this point,
# it doesn't matter if the definition for Main() appears
# before or after f1 and f2.
Main()

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: