Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 代码循环一次后,不会存储x和y值_Python_Python 3.x - Fatal编程技术网

Python 代码循环一次后,不会存储x和y值

Python 代码循环一次后,不会存储x和y值,python,python-3.x,Python,Python 3.x,我该如何设计这段代码,当我使它循环时,先前循环中的(x,y)值将存储在程序中。现在,如果我在程序中添加一个循环块,(x,y)值会随着每个输入而重置 question = (input("Where do you want to go?: ")); y = 0 x = 0 if question in ["up"]: y = y + 1 print("You've moved up one unit!") print("Your position is now ", x,

我该如何设计这段代码,当我使它循环时,先前循环中的(x,y)值将存储在程序中。现在,如果我在程序中添加一个循环块,(x,y)值会随着每个输入而重置

question = (input("Where do you want to go?: "));
y = 0
x = 0
if question in ["up"]:
    y = y + 1
    print("You've moved up one unit!")
    print("Your position is now ", x, y)

if question in ["down"]:
    y = y - 1
    print("You've moved down one unit!")
    print("Your position is now ", x, y)

if question in ["right"]:
    x = x + 1
    print("You've moved right one unit!")
    print("Your position is now ", x, y)

if question in ["left"]:
    y = y + 1
    print("You've moved left one unit!")
    print("Your position is now ", x, y)    

else:
    print("You can't go there.")

如果在每个输入中添加一个循环并重置x,y,听起来需要将x,y移出循环:

x=0
y=0
while True:
    # ask the question
    # process
而不是:

while True:
    # ask the question
    x=0
    y=0
    # process

应该在循环外部初始化x和y

y = 0
x = 0
while True:
   question = (input("Where do you want to go?: "))
   ...

否则,每次执行到循环的顶部时,这些行都会被执行

显示您是如何添加不起作用的循环的。“while true”语句是否有一些变化,会导致循环有条件地结束,而不是代码无限循环?在
while
循环中放置一个条件,或者在循环中执行类似于
if question==“quit”:break
break
关键字将退出循环。