[Tutor] Alan's responce frustrated beginner

Alan G alan.gauld at freenet.co.uk
Thu Sep 29 09:22:00 CEST 2005


>I want to save this file, import it and make the changes, eggs = 
>toast, spam
> = jelly and change the values if needed.
>
> def firstpart():
>   for n in range(0, 55):
>      if n % 3 == 0 or n % 7 == 0 or n % 11 == 0:
>          print 'eggs,',
>      else:
>          print 'spam,',

There are two approaches:

1) Use module level variales for the messages:

#### module testval ####

passMessage = 'eggs'
failMessage = 'spam'

def firstpart():
   for n in range(55):
     if n %3 ..... :
       print passMessage
     else: print failMessage

###########################

####### clientcode ########

import testval

testVal.passMessage = 'Milk'
testVal.failMessage = 'Honey'

testval.firstpart()

############################

2) Use function parameters

def firstpart(iterations, condition, passMsg, failMsg):
   for n in range(iterations):
     if condition:
       print passMsg
     else: print failMsg

firstpart(55,(n % 3 or n % 7 or n % 11), 'eggs','spam')
firstpart(55,(n % 3 or n % 7 or n % 11), 'Milk','Honey')

###########################

The second approach is probably best IMHO (whether you
parametereise the iterations and condition is optional,
it just makes the function as geeric as possible...)

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld 



More information about the Tutor mailing list