print("start")
start = {"x":20, "y":20};
print(start)
print("startingPos")
startingPos = start;
print(startingPos)
def refreshCoords(directions,startingPos):
if directions == "^":
startingPos = {"x":startingPos["x"], "y":startingPos["y"]+1};
if directions == "v":
startingPos = {"x":startingPos["x"], "y":startingPos["y"]-1};
return startingPos
if directions == ">":
startingPos = {"x":startingPos["x"]+1, "y":startingPos["y"]};
if directions == "<":
startingPos = {"x":startingPos["x"]-1, "y":startingPos["y"]};
def walker(direction,startingPos):
print(refreshCoords(direction,startingPos))
for i in range(1,10,1):
walker("v",startingPos)
我需要帮助解释,我不明白为什么在调用 walker("v",startingPos) 时,"Y" 只更改一次,然后值重复。它必须根据需要更改多次(在此示例中,调用函数时它从 20 更改为 10)。这段代码有什么错误?
关键是你在函数中改变局部变量
startingPos
的值而不以任何方式影响全局变量startingPos
这可以绕过,例如,
return