Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialfahad lashari
7,693 PointsIs 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
Iain Simmons
Treehouse Moderator 32,305 PointsYeah 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.
Ullas Savkoor
6,028 Pointsyou 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.
fahad lashari
7,693 Pointsfahad lashari
7,693 PointsYep I was going to do that just using a for loop and printing out the key's and values. Then just neatly arranging them.