[Tutor] how do I make my code better?

Danny Yoo dyoo at hashcollision.org
Tue Aug 19 01:41:48 CEST 2014


Hello,


Often, when you're writing code that looks roughly like:

#######################
a_1 = ...
a_2 = ...
...
a_n = ...

if ... a_1:
  ...
if ... a_2:
  ...
...
if ... a_n:
  ...
#######################

then your program is crying out to use a table.  The idea is to use a
list to structure the pieces into a single, tabular thing, so that you
can just point to an entry in the table to do something.

>From a brief glance, as a first pass, your code can be transformed to:

##########################################################
rounds = ["First Round players: [Jamaal Charles RB       KC], [LeSean
McCoy RB PHI], [Calvin Johnson     WR DET]",
          "Second round player: [Matt Forte RB CHI], [Eddie Lacy RB      GB],"
          "Third Round players: [Peyton Manning QB DEN], [Jimmy Graham
TE NO], [Demaryius Thomas WR DEN]",
          "[Dez Bryant WR DAL], [A.J. Green      WR      CIN],[
Brandon Marshall WR      CHI], [Julio Jones WR   ATL]",
]

answer = raw_input('Enter round number here: \n')

print rounds[int(answer)-1]
##########################################################

where the user now just enters a number, and that number is used to
lookup in the "rounds".  We use a list here to represent the table.


There may be other ways to improve this.  The entries in this table
are strings: maybe it makes sense for them to have some more
structure.  Depends on if you have more plans to expand the program
further.


More information about the Tutor mailing list