def main():
global currentX,currentY
currentX = 0
currentY = 0
currentlocation = currentX,currentY
print("Starting Location is", currentX,currentY)
print()
#Main menu dialouge
print("Please select direction:")
print("1, North;")
print("2, East;")
print("3, South;")
print("4, West;")
print("5, End this program")
#Loop = to 1 so while loop will go on indefitly until option 5 is pressed.
loop = 1
#try: handles all errors along with except:
try:
while loop == 1:
direction = input("--> ")
print()
direction = int(direction)
if direction == 1:
moveN = currentY + 1
print("Moved North.",currentlocation)
elif direction == 2:
currentX + 1
print("Moved East.",currentlocation)
elif direction == 3:
currentY - 1
print("Moved South.",currentlocation)
elif direction == 4:
currentX - 1
print("Moved West.",currentlocation)
elif direction == 5:
loop = 0
print("Final location is", currentlocation)
else:
print("ERROR:", choice, "is an invalid input.\n"
"Enter a number from 1 to 5.")
except: ValueError
print("Please enter a whole number between 1-5")
main()
我无法弄清楚为什么循环不会添加到currentlocation。 我得到一个输出 起始位置为0 0
Please select direction:
1, North;
2, East;
3, South;
4, West;
5, End this program
--> 3
Moved South. (0, 0)
--> 4
Moved West. (0, 0)
答案 0 :(得分:2)
您实际上并没有更改currentX和currentY,而只是评估您希望它们拥有的值。要更改它们,您需要分配给它们:
currentX = currentX + 1
或更简洁:
currentX += 1
你的方向1案也看起来。出于某种原因,您要分配给moveN
。我不知道应该做什么。
修改:您还需要更新currentlocation
以反映位置的变化。
答案 1 :(得分:1)
当你说
时currentlocation = currentX,currentY
你实际上并没有创建一个引用currentX和currentY的元组,你创建了一个元组,其中包含值在声明时的currentX和currentY中。因此,每次更改这些内容时,都不会更新。
解决此问题的一种方法是将currentlocation转换为函数。
def currentlocation():
return currentX,currentY
然后,而不是
print(currentlocation)
刚刚放
print(currentlocation())