python替代goto命令?

时间:2010-12-14 19:38:20

标签: python batch-file goto turtle-graphics

我有一个由龟图形组成的python程序,它基本上是要求用户绘制多少个正方形,然后在每个正方形之后,它使用以下内容将1添加到计数器:

counter=1
<drawing code here>
counter +=1

然后在那之后我想检查一下方块的数量是否等于用户输入的金额,如果是,那么我想去脚本的底部我会让它说出像完成!! 之类的东西。但是我不知道如何让它转到脚本的某个部分,因为我在python中不支持批处理的goto命令(我知道,goto = spaghetti代码)

我发现一个简单的解决方法就是下载一个有人制作的模块,让你可以将goto命令导入到python中并像批量一样使用它,但我想要一个原生的python解决方案,如果有的话!

我目前的代码是:

from turtle import *
import time
counter=1
color("red", "blue")
down()

user=int(raw_input('how many balls do you want?'))
counter +=1
if user===counter:

# solution goes here!

else:

for step in range(24):
        right(105)
        forward(100)
        right(105)
        forward(100)
        right(105)
        forward(100)
        right(105)
        forward(100)

up()
goto(120,0)
down()


counter +=1
if user==counter:

#solution goes here!

else:

for step in range(24):
        right(105)
        forward(100)
        right(105)
        forward(100)
        right(105)
        forward(100)
        right(105)
        forward(100)

up()
goto(0,-50)
write("Done!")

time.sleep(5) 

如果你有这个问题的答案或替代方案,我们将不胜感激!

4 个答案:

答案 0 :(得分:3)

这有帮助吗?

import turtle   # don't pollute the namespace
import time

def getInt(msg):
    return int(raw_input(msg))

def drawBall():
    turtle.down()
    for i in range(96):
        turtle.right(105)
        turtle.forward(100)
    turtle.up()

def moveOver():
    turtle.goto(120,0)

def Done():
    turtle.goto(0,-50)
    turtle.write('Done!')
    time.sleep(5)

def main(): 
    turtle.color('red','blue')
    for i in range(getInt('How many balls do you want?')):
        drawBall()
        moveOver()
    Done()

if __name__=="__main__":
    main()

不要考虑一长串指令。相反,可以考虑将问题分解为较小的行为,例如“画球”,并将每个行动都写成一个程序;然后考虑如何将这些程序结合在一起以实现您的目标。重复编写相同的代码表明你做错了。

答案 1 :(得分:2)

不要检查方格数然后再到最后,只需循环适当的次数,每次都画一个正方形。

答案 2 :(得分:0)

一些提示:

>>> def square():
    print "+--+"
    print "|  |"
    print "|  |"
    print "+--+"
    print


>>> range(5)
[0, 1, 2, 3, 4]
>>> for x in range(5):
    print x
    square()


0
+--+
|  |
|  |
+--+

1
+--+
|  |

[剪断]

答案 3 :(得分:0)

将代码细分为函数,然后在想要跳过函数的剩余代码时使用return

更新:我不一定宽恕一个功能的多个退出点,因为一个明显假设的评论者;这个答案是在问题的背景下。我对多重退出问题的看法与Tim Peters的that共同提出:

  

嗯,单退出是最好的,因为它总是使仪器更容易   经常使推理更容易(直到替代方案引入了这么多   goofy追踪那些的布尔标志比疾病更糟糕)。