is there a better way than replace to write this function? I am doing my homework and i have done this? Is there any other better way to do this?



def write_log(name, total):
    # change user input with shape names
    name = name.replace('1', 'triangle')
    name = name.replace('2', 'square')
    name = name.replace('3', 'rectangle')
    name = name.replace('4', 'pentagon')
    name = name.replace('5', 'hexagon')
    name = name.replace('6', 'octagon')
    name = name.replace('7', 'circle')

    total = int(total)

    logfile = open("text.txt", "a")

    if (total == 1):
       towrite = ('%i %s \n'
                  % (total, name))

    elif (total &gt;= 2 and total &lt;= 5):
       name += 's' # add s to name to make it plural
       towrite = ('%i %s \n'
                  % (total, name))
    else:
       towrite = ''
    try:
       logfile.write(towrite)
    finally:
       logfile.close()
    return
-- One --

You can use a dictionary to hold your translation data:

mydict = {'1':'triangle', '2':'square', '3':'rectangle',
          '4':'pentagon','5':'hexagon', '6':'octagon','7':'circle'}


Now your list of replacement lines becomes simply:

for key, value in mydict.iteritems():
    name = name.replace(key, value)


another option would be:

for key in mydict:
    name = name.replace(key, mydict[key])


To make this part complete, consider also a tuple for holding your data as indicated in @larmans answer. See also comments in the answers. I think there are interesting hints about which could be the best alternative for different cases.

-- Two --

also remember you can do

2 &lt;= total &lt;= 5


instead of

total &gt;= 2 and total &lt;= 5


-- Three --

Note you dont need parenthesis in the if expressions. Just do this:

if total == 1: