我究竟做错了什么?和/或在Python中

时间:2014-03-19 00:05:16

标签: python

对不起,我是新来的。

以下是问题:

编写一个程序,将棋盘上的位置作为列col和行值行,并检查该位置是否有效。请记住,棋盘中的列是从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."

提前致谢!

3 个答案:

答案 0 :(得分:1)

添加一些括号以确保处理所有列检查与行查询:

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."
顺便说一下,您的代码没有检查列= 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)

答案 1 :(得分:0)

你必须使用括号

答案 2 :(得分:0)

你忘记了括号!你需要它们,因为,就像在数学中一样,它会首先在括号中完成所有事情,然后再做其他事情。