[Tutor] Why does the last loop not work?
Alan Gauld
alan.gauld at btinternet.com
Tue Feb 25 11:44:15 CET 2014
On 25/02/14 00:59, Gregg Martinson wrote:
> there is nothing produced. I am pretty sure it has to do with my syntax
> for the list and the substitution of a a local variable
Chris has answered your question but there are a couple
of general points on your code below...
> def header (r):
> print ("##############################")
> print ("### Round: ",r," ####")
> print ("##############################")
> print ("Aff\tNeg\tJudge\tRoom")
Rather than having multiple calls to print you could do the same thing
with a single call using a triple quoted string. Its largely a matter of
taste.
> class Team(object):
> code = ""
This makes code a class level attribute. I don't think that's
what you want. And you don't seem to use it anywhere.
> # The class "constructor" - It's actually an initializer
> def __init__(self,code):
> self.code = code
This creates an instance attribute which is distinct to your class
variable above.
> print ("code is: ",code)
> self.competitors=[]
> def print_team(self):
> print("team code is: ",self.code)
> print("debated:",end=" ")
> for x in self.competitors:
> print (x)
>
> def debated(self,otherTeam):
> print (x)
> self.competitors.append(x)
> def giveCode(self):
> return self.code
In Python its idiomatic to not use getter methods like this.
Unless you need to use a method you can just access code
directly.
> def make_team(code):
> team = Team(code)
> return team
Unless you u=inrtend to do more magic here this is pretty much redundant.
Calling
spam = make_team(code)
is no better than calling
spam = Team(code)
And it takes more typing, more reading to understand and is slower.
> #MAIN Program#
> myTeamCodes=["a","aa","b","bb","c","cc","d"]
> # Make teams
> myTeams=[]#list of teams
> for x in myTeamCodes:
> myteam=make_team(x)
> myTeams.append(myteam)
I don't know if you've discovered list comprehensions yet but this
pattern is exactly what they do
somelist = []
for item in anotherList:
somelist.append(somefunc(item)
So when you see that pattern consider replacing it with:
someList = [someFunc(item) for item in anotherList]
Or in your case:
myTeams = [Team(code) for code in myTeamCodes]
HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list