Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Object-Oriented Python (retired) Inheritance Instance Methods

fahad lashari
fahad lashari
6,771 Points

Is adding specific data directly into the code bad?

Kenneth solved the problem of limiting the players weapon choice by doing:

if weapon_choice in 'sab':
            if weapon_choice == 's':
                return 'sword'
            elif weapon_choice == 'a':
                return 'axe'
            else:
                return 'bow'
        else:
            return weapon_choice()

Now let's say I want to another 20 weapons. Would this like of if else scenario make using the above method very limited.

WEAPONS = {"a":"axe", "b":"bow", "s":"sword"}

    def get_weapon(self):
        weapon_choice = input("Choose your weapon. [S]word, [A]xe or [B]ow: \n>").lower()
        for key, value in WEAPONS.items():
            if key == weapon_choice:
                    return value
        if weapon_choice not in WEAPONS:
                    return self.get_weapon()

I tried to use a dictionary instead and just typed some code that would work with any amount of weapons. It works just as fine. I am curious however to know, is my approach non-conventional? am I missing something or doing something wrong?

I know how the code can be improved to accommodate the need for returning the specific weapon if let's say two weapons started with the same letter. However for the sake of simplicity I haven't implemented the improvement into the code yet.

Do let me know what you think.

kind regards,

Fahad

2 Answers

Yeah that works, and is much more reusable, though you'd probably also want to find a way to print the list of available weapons without having to explicitly write them into the input prompt. You'd probably want to store that as a string variable and then output it in the input prompt.

fahad lashari
fahad lashari
6,771 Points

Yep I was going to do that just using a for loop and printing out the key's and values. Then just neatly arranging them.

you could remove the second if condition since you will come out of for loop when no choices have been met and also the 'return' in return self.get_weapon is redundant since there are no statements after that.