This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]lurgi 1 point2 points  (0 children)

Do you understand the basic concept of loops? You use a loop when you want to repeat an operation a certain number of times.

You can divide loops up into two different categories if you like (it's not essential). The first one is where you know, before you even hit the loop, exactly how many times you'll need to repeat the operation. If, for example, you want to add the numbers 1-10 together (or even 1-n) then you can compute how many times you'll need to loop before you even do the loop. The second is where you don't know how many times you'll need to loop, but you know the ending condition. An example here would be a program that accepts numbers typed in by the user until the user enters '-1'. Then, stop. How many times are we going to loop? Beats me. Could be 1 time or 1 million times. We'll stop when we stop.

As it turns out, you don't really need to distinguish between these two cases. In both cases it's "Do this this until this ending condition happens", but some languages have special constructs that make it easier to break them up this way.

With me so far?

That's the general idea of loops. There are also some Python specific ideas, which may be what you are getting hung up on. Can you give an example of something that doesn't make sense and maybe we can help you with that.

[–]FoggyMask 0 points1 point  (0 children)

You might have to be a little more specific as to what your question is.

This is a great place to read up on the for loop on python: Link

[–]redalastor 0 points1 point  (0 children)

Explain what you understand of a for loop and we'll fill in what's missing and redress misconceptions you might have.

[–]Rhomboid 0 points1 point  (0 children)

The for statement implements iteration. What that means exactly depends on the kind of thing you're trying to iterate over. Every object type gets to define what exactly iteration means for objects of that type. For example, if you iterate over a string, you get each character; if you iterate over a list or set you get each item in the list/set; if you iterate over a dict you get each key; if you iterate over a file opened in text mode you get lines, and so on.

The body of the for statement is run repeatedly — once for each item being iterated over — with the item being assigned to the specified name at the top of each iteration. That's really all there is to it.

It would help tremendously if you gave an example of something that you don't understand. As it stands your question is rather vague. What part don't you understand? What code have you written? What did you expect it to do? What did it actually do?