[Tutor] functions first?

Alan Gauld alan.gauld at btinternet.com
Tue Jan 27 09:15:38 CET 2015


On 27/01/15 02:04, Alex Kleider wrote:
> Please correct me if I am wrong, but I've assumed that it is proper to
> define all functions before embarking on the main body of a program.

No, you can do it either way round. Top-Down or Bottom-Up as they are known.

Usually its a muxture of both.

But most folks like to have a running program at all times. So you might 
write the function headers with dummy bodies then write the main code 
that calls the functions. Then go back and fill in the functions one at 
a time, for example.

eg. A trivial example:

### pass 1 ################################

def sayHello(msg):
    pass

def getGreeting(prompt):
     return "hello world"

def main():
    greeting = getGreeting("What to say: ")
    sayHello(greeting)

if __name__ == "__main__": main()

### pass 2 ##############################

def sayHello(msg):
    print(msg)

def getGreeting(prompt):
     return "hello world"

def main():
    greeting = getGreeting("What to say: ")
    sayHello(greeting)

if __name__ == "__main__": main()

### pass 3  ##############################

def sayHello(msg):
    print(msg)

def getGreeting(prompt):
     return input(prompt)

def main():
    greeting = getGreeting("What to say: ")
    sayHello(greeting)

if __name__ == "__main__": main()

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list