简体   繁体   English

如何在 Python 的 for 循环中设置条件语句?

[英]How to set a conditional statement within a for loop in Python?

I am using turtle in python to create simple shapes that have a change of gradient starting at white and ending at black, black is 0,0,0.我在 python 中使用乌龟来创建简单的形状,这些形状的渐变从白色开始到黑色结束,黑色是 0,0,0。 The way I have it set up currently is that it will continue to subtract beyond zero within my nested loop.我目前设置它的方式是它会在我的嵌套循环中继续减去超过零。 I want my code to print the color black once it equals or is less than 0,0,0.我希望我的代码在等于或小于 0,0,0 时打印黑色。 I would appreciate it if someone could give me pointers and hints without straight up giving me the solution.如果有人能在不直接给我解决方案的情况下给我指点和提示,我将不胜感激。 Thanks!谢谢!

a = int(input("Enter int angle:"))
q = int(input("Enter int length:"))
print("Click turtle screen to exit...")
r=1
g=1
b=1
import turtle
wn = turtle.Screen()
wn.bgcolor("white")
alex = turtle.Turtle()
alex.speed(500)
alex.pencolor("white")
for i in range (q):      
   alex.forward(i)
   alex.left(a)
   for c in range (q):
      alex.pencolor(r,g,b)
      r=(r-.0001)
      g=(g-.0001)
      b=(b-.0001)

    
wn.exitonclick()

In your final for loop, you should have在你最后的 for 循环中,你应该有

for c in range (q):
      alex.pencolor(r,g,b)
      if condition (color is black or less than black):
          result (print black)
      else:
          r=(r-.0001)
          g=(g-.0001)
          b=(b-.0001)

If we make the color decrement 1 over the number of iterations, then the color should reach black on our last iteration:如果我们在迭代次数上使颜色递减 1,那么颜色应该在我们最后一次迭代时变为黑色:

from turtle import Screen, Turtle

screen = Screen()

angle = screen.numinput("Angle", "Enter angle: ", default=110, minval=1, maxval=359)
length = int(screen.numinput("Length", "Enter integer length: ", default=75, minval=10, maxval=200))

gray = 1.0

turtle = Turtle()
turtle.speed('fastest')

for _ in range(length):
    turtle.pencolor(gray, gray, gray)
    turtle.forward(length)
    turtle.left(angle)

    gray = gray - 1.0 / length

screen.exitonclick()

But, if that still gives you problems, you can wrap it in a max() :但是,如果这仍然给您带来问题,您可以将其包装在max()

    gray = max(0, gray - 1.0 / length)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM