我对编程一般都很陌生,虽然我确信这看起来像作业,但它可能是有人,但我在教自己,所以它是“自我作业”?在python中,如何计算函数内满足条件的次数?
无论如何,我想统计一只乌龟离开窗户的次数,因为它随机做出正方形。我也想在它离开屏幕的每一点上放一个点,但那只是为了我自己的乐趣。
我知道我每次都设置为0,但我不知道如何创建一个累加器模式(如果这是正确的事情)在这样的函数内已经必须返回一个值。
这里是我的代码:
import random
import turtle
def isInScreen(w,t):
leftBound = - w.window_width()/2
rightBound = w.window_width()/2
topBound = w.window_height()/2
bottomBound = -w.window_height()/2
turtleX = t.xcor()
turtleY = t.ycor()
stillIn = True
outs = 0
if turtleX > rightBound or turtleX < leftBound:
t.dot()
t.right(180)
t.forward(50)
outs += 1
print(outs)
return outs
if turtleY > topBound or turtleY < bottomBound:
t.dot()
t.right(180)
t.forward(50)
outs += 1
print(outs)
return outs
if outs == 4:
stillIn = False
return stillIn
t = turtle.Turtle()
wn = turtle.Screen()
t.shape('turtle')
while isInScreen(wn,t):
coin = random.randrange(0,2)
if coin == 0:
t.left(90)
else:
t.right(90)
t.forward(50)
wn.exitonclick()
任何意见,将不胜感激。
对不起,但我似乎无法让您的答案正常工作。绘图循环在4之后结束,否则永不结束。 – theSchap 2012-07-18 00:32:53