Why does else function run even the elif statement is true?

Question:

I’m working on a take home exam and I completed it but only for one sample test it doesn’t work. Here is my code:

h = 'abcdefgh'
v = '12345678'
h_knight = (input('Please enter horizontal position of the knight (a,b,c,d,e,f,g,h): ')).lower()
if len(h_knight) != 1 or h_knight.isalpha() is False:
  print('Horizontal input for knight is not a letter')  
elif not (h_knight) in h:
  print('Horizontal input for knight is not a proper letter')
else:  
  v_knight = (input('Please enter vertical position of the knight (1,2,3,4,5,6,7,8): '))
  if v_knight.isdigit() == False:
    print('Vertical input for knight is not a number')
  elif v_knight.isdigit() == True and v_knight not in v:
    print('Vertical input for knight is not a proper number')
  else:
    h_bishop = (input('Please enter horizontal position of the bishop (a,b,c,d,e,f,g,h): ')).lower()
    if len(h_bishop) != 1 or h_bishop.isalpha() is False:
      print('Horizontal input for bishop is not a letter')
    elif not (h_bishop) in h:
      print('Horizontal input for bishop is not a proper letter')
    else:    
      v_bishop = (input('Please enter vertical position of the bishop (1,2,3,4,5,6,7,8): '))
      if v_bishop.isdigit() == False:
        print('Vertical input for bishop is not a number')
      elif v_bishop.isdigit() == True and v_knight not in v:
        print('Vertical input for bishop is not a proper number')
      else:
        idx1 = h.find(h_knight)
        idx2 = v.find(v_knight)
        idx3 = h.find(h_bishop)
        idx4 = v.find(v_bishop)
        if idx1 == idx3 and idx2 == idx4:
          print("They can't be in the same square")
        elif abs(idx1 - idx3) == 2 and abs(idx2 - idx4) == 1:
          print('Knight can attack bishop')
        elif abs(idx1 - idx3) == 1 and abs(idx2 - idx4) == 2:
          print('Knight can attack bishop')
        else:
          if abs(idx1 - idx3) != abs(idx2 - idx4):
            print('Neither of them can attack each other')
          else:
            print('Bishop can attack knight')

Inputs for the sample test which doesn’t work: h,1,h,9.
It’s supposed to display ‘Vertical input for bishop is not a proper number’ but instead it displays ‘Neither of them can attack each other’which is an else condition as you can see above. I appreciate any suggestions to fix it.

Asked By: Emre Sen

||

Answers:

You never check if the bishops postition is in v

This

elif v_bishop.isdigit() == True and v_knight not in v:
                print('Vertical input for bishop is not a proper number')

Should be this:

elif v_bishop.isdigit() == True and v_bishop not in v:
                print('Vertical input for bishop is not a proper number')

I guess you copy pasted and didn’t change it

Answered By: Domi
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.