Order of execution and style of coding in Python

The defs are just creating the functions. No code is executed, other than to parse the syntax and tie functions to those names.

The if is the first place code is actually executed. If you put it first, and call a function before it is defined, the result is a NameError. Therefore, you need to put it after the functions are defined.

Note that this is unlike PHP or JavaScript, where functions are ‘hoisted’ – any function definitions are processed and parsed before everything else. In PHP and JavaScript, it’s perfectly legal to do what you are saying and define functions in the source lower down than where they are called. (One detail in JS is that functions defined like function(){} are hoisted, while functions defined like var func1=function(){}; are not. I don’t know how it works with anonymous functions in PHP 5.3 yet).

See, in this, cat() will print correctly, and yip() gives you a NameError because the parser hasn’t gotten to the definition of yip() at the time you call it.

def cat():
  print 'meowin, yo'

cat()

yip()

def yip():
  print 'barkin, yall'

meowin, yo
Traceback (most recent call last):
File “cat.py”, line 5, in
yip()
NameError: name ‘yip’ is not defined

Leave a Comment