总的来说,我对编程还很陌生,虽然我确定这看起来像是家庭作业,但它可能是给某人的,但我是在自学,所以这是“自学作业”?
无论如何,我想计算乌龟在随机生成正方形时离开窗口的次数。我还想在它离开屏幕的每个点上都放一个点,但这只是为了我自己的乐趣。
我知道我每次都将 outs 设置为 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()
如有任何建议,我们将不胜感激。
最佳答案
最简单的方法是跟踪你的乌龟在你的函数之外但在你的 while
循环内离开屏幕的次数。
与其让您的函数返回乌龟是否已经出去四次,不如让它在该步骤中出去时返回。您必须将函数更改为如下所示:
def isScreen(w, t):
if turtleX > rightBound or turtleX < leftBound:
return True
if turtleY > topBound or turtleY < bottomBound:
return True
else:
return False
然后你可以在 while
循环中记录你出去了多少次:
outs = 0
while outs < 4:
if isScreen:
outs += 1
关于python - 在 python 中,如何计算函数中满足条件的次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11528682/