Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.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 在循环内更改全局变量_Python_Loops_Variables - Fatal编程技术网

Python 在循环内更改全局变量

Python 在循环内更改全局变量,python,loops,variables,Python,Loops,Variables,(这可能是一个愚蠢的问题,我对python很陌生) 我想使用用户输入使海龟移动,使其移动效果很好,但我想更改海龟的颜色,并使颜色在循环中保持不变。我不知道该怎么做,也不知道该做些什么,所以我在这里问 多谢各位 import turtle t = turtle.Turtle() times = int(input("How many points would you like to draw?")) for side in range (times): move = in

(这可能是一个愚蠢的问题,我对python很陌生) 我想使用用户输入使海龟移动,使其移动效果很好,但我想更改海龟的颜色,并使颜色在循环中保持不变。我不知道该怎么做,也不知道该做些什么,所以我在这里问

多谢各位

import turtle    

t = turtle.Turtle()

times = int(input("How many points would you like to draw?"))


for side in range (times):

    move = input("which way would you like too go?\n\n1: Forward\n2: Backward\n3: Right\n4: Left\n5: Change Color\n6: Exit")

    if (move == str(1)):
        t.forward(50)

    if (move == str(2)):
        t.backward(50)

    if (move == str(3)):
        t.right(90)

    if (move == str(4)):
        t.left(90)

    if(move == str(5)):
        color = input("What color would you like?")
        t.color(color)

    if (move == str(6)):
        break

    else:
        break
只要紧跟在它前面的
if
为False,就会执行此
else

else:
    break
因此,只要
move
不是
6
,循环就会结束

如果只想在
move
不是1或2或3或4或5或6时中断,请将所有
If
s(第一个除外)更改为
elif
s

if (move == str(6)):
    break

将所有
if
语句(第一个语句除外)更改为
elif
。问题是末尾的
else:
仅附加到
if(move==str(6)):
,因此除了
6
之外的任何移动都会导致您跳出循环

if (move == str(1)):
    t.forward(50)

elif (move == str(2)):
    t.backward(50)

elif (move == str(3)):
    t.right(90)

elif (move == str(4)):
    t.left(90)

elif(move == str(5)):
    color = input("What color would you like?")
    t.color(color)

elif (move == str(6)):
    break

else:
    break

另外,只需编写
'1'
而不是
str(1)
。或者将输入转换为
int
,然后在move==1时使用

使用
t.color()
更改海龟颜色。您已经编写了更改颜色的代码。这怎么不起作用?欢迎来到StackOverflow。请阅读并遵循帮助文档中的发布指南。适用于这里。在您发布MCVE代码并准确描述问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中,并重现您描述的问题。@Prune它会改变颜色,但会打破循环为什么要中断?如果你用一次中断来击败它,你的for循环在做什么?else:break…将结束循环Regardless另一件值得注意的事情是,第一次将
移动到一个整数,而不是在每次比较中将每个整数连续转换为一个字符串,这样会更干净。或者使用文本字符串,例如
'1'
而不是
str(1)
if (move == '1'):
    t.forward(50)

elif (move == '2'):
    t.backward(50)

elif (move == '3'):
    t.right(90)

elif (move == '4'):
    t.left(90)

elif(move == '5'):
    color = input("What color would you like?")
    t.color(color)

elif (move == '6'):
    break

else:
    break