Can anyone explain me Python for loop (or iteration) algorithm

限于喜欢 提交于 2021-02-05 09:33:25

问题


I am learning python from Coursera . I have written one program , According to that when I click on the screen , it draws circle . See the program below --

# Dots

# importing
import simplegui
import math

width = 600
height = 600
ball_list = []
radius = 20
colour = "Yellow"

# position ditector
def distance(p,q) :
    return math.sqrt((p[0]-q[0])**2 + (p[1]-q[1])**2)



# Mouse click -- Change the position
def click(pos) :
    ball_list.append(pos)
#    global position
#   global colour
#    if  distance(pos, position) < radius :
#        colour = "Blue"
#    else :
#        position = list(pos)
#        colour = "Yellow"


# Drawing the ball
def draw(canvas) :
    for position in ball_list :
        canvas.draw_circle(position , radius , 2, "Black" , colour)

# Creating the frame
frame = simplegui.create_frame("Dots" , 600,600)
frame.set_canvas_background("White")

frame.set_draw_handler(draw)

# mouse click 
frame.set_mouseclick_handler(click)


# Start
frame.start()

But my doubt is in def draw(canvas), for position in ball_list , I have not defined any position . I made position = list(pos) as comment . Then what is the value of position in position in ball_list , How can for loop work without any value ? What is iteration ? What is the difference between for loop and iteration ?

If above code doesn't work in your IDE, please go to http://www.codeskulptor.org/#user38_VSZ0jZ0uTh_0.py and run it .


回答1:


for loop in python is little bit different compared to other languages. I'll try explaining with code you have written.Every time you call the click function then you are appending the pos to the list called ball_list which you need to draw the circle.

def click(pos) :
    ball_list.append(pos) ## appends the pos to ball_list

Now after you have list with pos then you call the following function.

def draw(canvas) :
    for position in ball_list :
        canvas.draw_circle(position , radius , 2, "Black" , colour)

Here the variable position iterates through all the pos that you have appended to the list ball_list starting from first till last value. And if you are wondering how and what is the value of position variable then print it's value and see it for yourself like the following:

def draw(canvas) :
        for position in ball_list :
            print position  ## prints one pos value in the ball_list for each iteration.
            canvas.draw_circle(position , radius , 2, "Black" , colour)



回答2:


a_list = [1, 2, 3, 4, 5, 6, 7]

for x in [10, 20, 30, 40, 50]:
    print x

10 20 30 40 50

for x in a_list:
   print x

1 2 3 4 5 6 7

for i in range(10):
    print i

1 2 3 4 5 6 7 8 9 10




回答3:


Say you have your own class that you want it to be iterable:

 class MyRange(object):
     def __init__(self, low, high):
         self.low = low
         self.high = high

     def __iter__(self):
         low = self.low
         while self.high >= low:
             yield low
             low += 1

Now you can:

r = MyRange(1, 10)
for number in r:
    print number,

number now have the value returned from __iter__ in each iteration. That's how things work in Python, and in your case, you have a list, which has it's own __iter__ and used in a similar way.




回答4:


In python, for x in y: iterates through every item in y, and assigns the value of the current iteration to the variable x so that you can reference that value inside the body of the for loop. Here's an eval.in that might help you see how it works.

Screenshot of the eval.in

Here's a brief comparison to Java, assuming that the variable "arrayList" is an ArrayList (Java) or list (Python) of things, and you want to call the method do_something_with() on each value in the list.

Python:

for x in arrayList:
    do_something_with(x)

Java:

for (int i = 0; i < arrayList.size(); i++) {
    do_something_with(arrayList.get(i));
}

Fundamentally, you COULD write Python that looks more like the Java:

for x in range(0, len(arrayList)):
    do_something_with(arrayList[x])

This code would do the exact same thing. However, Python realized that this is a common enough task that there was value in providing a level of abstraction for it (often called "syntactic sugar" in programming languages). You can read more about Python iterators, and how different kinds of data get iterated, in the python documentation.



来源:https://stackoverflow.com/questions/26522431/can-anyone-explain-me-python-for-loop-or-iteration-algorithm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!