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 trial

Python

When I put sab on weapon selection (for a test), it'll accept and bow will be the weapon.

Like:

from character import Character
p = Character()
Name: Andrew
Weapon ([S]word, [A]xe, [B]ow): sab
p.weapon
'bow'

Why? Is there an error at if/else statements ?

def get_weapon(self):
    weapon_choice = input("Weapon ([S]word, [A]xe, [B]ow): ").lower()
    if weapon_choice in 'sab':
      if weapon_choice == 's':
        return 'sword'
      elif weapon_choice == 'a':
        return 'axe'
      else:
        return 'bow'
    else:
        return self.get_weapon()

2 Answers

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

Because "sa", "ab", and "sab" are all in the string "sab". Since "sab" isn't "s" or "a", both of which are tested against explicitly, it falls into the else and sets your weapon to the bow.

I'm sorry, I was cruising around the forum trying to help people but I noticed that this also happens with my code. I tried all other combinations of those letters and noticed that 'sab' is the only combination that is accepted by the code and treated as if I entered 'b'.

I'm curious now!