You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python国际象棋校验程序:elif生效时else仍执行的原因及修复

国际象棋骑士与主教位置校验程序BUG排查与修复

测试输入为h,1,h,9时,程序未输出预期的Vertical input for bishop is not a proper number,反而输出Neither of them can attack each other。

问题代码

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')

错误原因

问题出在主教垂直位置合法性校验的分支中:代码错误地使用v_knight not in v作为判断条件,而非v_bishop not in v。测试用例中骑士的垂直位置是1(属于合法范围),导致该条件永远不成立,程序跳过错误提示,直接进入后续攻击判断逻辑,最终输出错误结果。

修复建议

将主教垂直位置校验的elif条件中的v_knight替换为v_bishop,修正后的代码片段如下:

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

内容的提问来源于stack exchange,提问作者Emre Sen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 13:45:29