简体   繁体   中英

Question about for loops in turtle functions and also in general

Question about for loops in general:

I am new to Python was wondering what the purpose of "for loops" is? What do they do in a function/what output do they produce? When are they used?

(I've done some research on what a for loop is, but most sources are confusing/unclear so I decided to ask on here.)

Question about using for loops in turtle:

Is the for loop function required in the following code dealing with filling in colors of a shape? I've seen some people use it when demonstrating examples of filling in color, but I'm not quite sure if it's required or what it does.

# Example code: I know, nothing is shown 
# because I haven't told the function to draw anything, this is just an example.

t.pencolor("blue")
t.fillcolor("blue")
t.begin_fill()
for i in range(4):
    # remove 'pass' and write some code here, for loop is not doing any thing.
    pass
t.end_fill()

# I noticed that this code produced the same output as:

t.pencolor("blue")
t.fillcolor("blue")
t.begin_fill()
t.end_fill()

You use a for loop whenever you need to do the same thing over and over (a) .

For example (using your "turtle" area of concern), say you wanted to draw a circle (or something approximating a circle). You could do this with something like:

pen down
for i in 1..360:
    go forward 1 unit
    turn right one degree
pen up

The alternative would be a rather long sequence of commands of the form:

    got forward 1 unit
    turn right one degree
    got forward 1 unit
    turn right one degree
    got forward 1 unit
    turn right one degree
    : :
    got forward 1 unit
    turn right one degree

which nobody wants to read or debug:-)


(a) The way I teach beginners is to basically introduce them to the three main concepts of program flow:

  • sequence, doing things sequentially in order;
  • iteration, doing a similar thing many times; and
  • selection, doing different things based on conditions.
for i in range(4):
  t.forward(150)
  t.right(90)

change range(1), range(2), range(3) then you will be able to see beauty of for loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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