【发布时间】:2020-11-07 12:35:21
【问题描述】:
我几天前刚开始学习 Python。我正在开发一个国际象棋游戏,而我遇到的问题是确定玩家想要下的棋子位置的代码。如果我输入一个包含两个数字的字符串,该函数会将它们解析出来并分配它们以及 y 和 x 值。
但是,如果在字符串中只找到一个数字或没有找到数字,它会打印“No digits or not enough numbers found”,让您重新输入一个字符串,然后再次调用该函数。我的问题是,在它调用自己之后,如果你输入一个有效的字符串,它会识别数字,将它打包到一个列表中,就像它应该做的那样,但不会返回任何东西。我检查以确保列表已正确填写,它只是返回无。
这是错误:
Traceback (most recent call last):
File "C:\Users\Jack\PycharmProjects\Messing With 2D Lists\Messing With 2D Lists.py", line 91, in <module>
piece_num = position[0]
TypeError: 'NoneType' object is not subscriptable
这是调用函数的代码,最后一行是触发错误的代码,因为它接收的不是一个列表,而是一个无类型:
posit = input("Choose your piece\nEnter coordinates: ")
position = piece_position(posit)
print(position)
piece_num = position[0]
这里是“棋盘”,如果你想重现我的错误,因为它在代码中被引用。
chess = [
[1, 2, 1, 2, 1, 2, 1, 2],
[2, 1, 2, 1, 2, 1, 2, 1],
[1, 2, 1, 2, 1, 2, 1, 2],
[2, 1, 2, 1, 2, 1, 2, 1],
[1, 2, 1, 2, 1, 2, 1, 2],
[2, 1, 2, 1, 2, 1, 2, 1],
[1, 2, 1, 2, 1, 2, 1, 2],
[2, 1, 2, 1, 6, 1, 2, 1],
]
这里是确定棋子位置的函数:
def piece_position(pos):
num1d = False
num2d = False
for char in pos:
if not num1d:
if char.isdigit():
num1 = int(char) - 1
num1d = True
else:
pass
elif not num2d:
if char.isdigit():
num2 = int(char) - 1
num2d = True
else:
pass
print(num1d)
print(num2d)
if num1d and num2d:
print(num1, num2)
result = [chess[num1][num2]]
result.append(num1)
result.append(num2)
print(result)
return result
else:
print("No digits or not enough digits found")
posit2 = input("Choose your piece\nEnter coordinates: ")
piece_position(posit2)
我还知道当它翻转时我将其称为 posit2 而不是仅是 posit,并且该变量正在询问 posit 的结果,但是将其更改为 posit 或 posit2 似乎没有任何区别。
请随意提出建设性的组织批评,我还是 Python 的新手,并且还在摸索中,我知道我还有很多需要改进的地方,还有很多我不明白的地方。
【问题讨论】:
-
你只需要调用带有return语句的递归函数:
return piece_position(posit2) -
@SerialLazer 感谢您的快速回复!我究竟会把它放在哪里?我是否需要一些索引来标记它是否是第二次或更长时间运行,如果是则返回你说的递归语句?
-
只需将 return 添加到调用递归函数的代码的最后一行。
-
@SerialLazer 谢谢,在你回复之前我意识到,我很感激!
-
另外,最好使用while循环而不是在其内部调用函数
标签: python python-3.x return-type