Sign up ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I am creating a simple Boxing sim engine and have got things working fairly well. A few months ago I was instructed to avoid copy and pasting code and to try and "conserve my logic".

Anyways, I feel I have done a fairly good job overall but there is one area (posted below) that I feel definitely has room for improvement:

print ("1)Joe Smith\n2)Mike Jones\n3)Steve Roberts\n")
boxer1 = input("Choose a fighter: ")
boxer2 = input ("Choose his opponent: ")
if boxer1 == '1':
    B1 = JS
elif boxer1 == '2':
    B1 = MJ
elif boxer1 == '3':
    B1 = SR
if boxer2 == '1':
    B2 = JS
elif boxer2 == '2':
    B2 = MJ
elif boxer2 == '3':
    B2 = SR

MJ, JS, and SR are all variables for objects in my Boxer class. My concern is that I will have to continue adding four lines of code for each boxer I add to the program. While I don't mind typing each line out, I realize there may be a much more efficient way to approach this that I'm not seeing. I realize this isn't a major issue but, as I mentioned, this program is mainly for practice and therefore I want to make sure I'm programming as efficiently as possible.

share|improve this question

1 Answer 1

up vote 2 down vote accepted

Assuming that each Boxer object has a .name attribute…

BOXERS = [None, JS, MJ, SR]
for i in range(1, len(BOXERS)):
    print("%d) %s" % (i, BOXERS[i].name))
boxer1 = BOXERS[int(input("Choose a fighter: "))]
boxer2 = BOXERS[int(input("Choose his opponent: "))]

You want to generate the menu using the names already in the boxer objects, and retrieve the result with an array lookup.

Note that with this solution, you'll get an IndexError if the user picks an invalid entry. You should decide how such errors should be treated, since your original code also lacked error handling.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.