[英]What am I doing wrong? and/or in Python
抱歉,我是新来的。
这是问题:
编写一个程序,该程序将在国际象棋棋盘上的位置作为列col和行值row,并检查该位置是否有效。 请记住,国际象棋棋盘中的列是从A到H(含)的字母,而行是1到8(含)之间的数字。 A3或E7是有效输入,但a1或L5不是有效输入。 如果两个坐标均有效,例如E2,则程序将打印“将工件移至E2。”,否则将打印“位置无效”。
这是我的代码:
if row <9 and col == 'A' or col == 'B' or col == 'C' or col == 'D' or col == 'E' or col == 'F' or col == 'G' or col == 'H':
print "The piece is moved to",col,row,"."
else:
print "The position is not valid."
提前致谢!
放入一些括号以确保所有列检查与行查询均得到处理:
if row <9 and (col == 'A' or col == 'B' or col == 'C' or col == 'D' or col == 'E' or col == 'F' or col == 'G' or col == 'H'):
print "The piece is moved to",col,row,"."
else:
print "The position is not valid."
顺便说一句,您的代码不检查column = 0,更简单的方法是说:
if (row in range(1,9) and col in "ABCDEFGH"):
您可以使用.format()
或%
运算符一起打印字符串:
print "The piece is moved to {}{}.".format(col,row)
要么
print "The piece is moved to %s%d." % (col,row)
你必须用括号
你忘了括号! 您需要它们,因为像数学一样,它将首先执行括号中的所有操作,然后执行其他操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.