在循环中更改全局变量

时间:2017-06-22 16:21:09

标签: python loops variables

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

(这可能是一个愚蠢的问题,我对python很新) 我想使用用户输入使乌龟移动,并使其移动工作正常,但我想改变乌龟的颜色并使颜色在循环内保持不变。我不知道该怎么做或研究什么,所以我在这里问。

谢谢

2 个答案:

答案 0 :(得分:2)

else:
    break

只要前面的else为False,就会执行if

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

只要move不是6,您的循环就会结束。

如果您只想在move不是1或2或3或4或5或6时中断,请将除{1}之外的所有if更改为elif

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 :(得分:2)

将除{1}之外的所有if语句更改为elif。问题是最后的else:仅附加到if (move == str(6)):,因此6以外的任何移动都会导致您退出循环。

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

此外,只需撰写'1'而不是str(1)。或者将输入转换为int,然后只使用if move == 1: