3

I'm trying to create a for loop and I ran into problems. I don't understand how these loops work, and I think the problem is because I'm using the for syntax incorrectly.

From what I understand, a for loop should look like

for w in words:
    print(w, len(w))

But how exactly does it work?

To try to be specific: What does the w mean? How can I know what to write between for and in, and after in? What exactly happens when the code runs?


For a more technical breakdown of how for loops are implemented, see How does a Python for loop with iterable work?.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
musha1
  • 65
  • 2
  • 4
  • 6
    Other languages call it a 'foreach' loop, if that helps. – roippi Oct 08 '13 at 20:37
  • I'm surprised that I haven't seen more demand for a canonical like this. The equivalent of this question is asked **constantly** on the r/learnpython subreddit. – Karl Knechtel Jul 30 '22 at 03:13
  • Hmm. Looking further into the original question... while OP *was asking*, superficially, about the syntax, it seems that the underlying problem is that OP wanted to iterate over a list of numbers, but didn't **have** a list of numbers to iterate over. If asked today and I saw it in the original form, I would have instead closed it as a duplicate of [Get a list of numbers as input from the user](https://stackoverflow.com/questions/4663306). – Karl Knechtel Jan 25 '23 at 06:58

4 Answers4

4

A for loop takes each item in an iterable and assigns that value to a variable like w or number, each time through the loop. The code inside the loop is repeated with each of those values being re-assigned to that variable, until the loop runs out of items.

Note that the name used doesn't affect what values are assigned each time through the loop. Code like for letter in myvar: doesn't force the program to choose letters. The name letter just gets the next item from myvar each time through the loop. What the "next item" is, depends entirely on what myvar is.

As a metaphor, imagine that you have a shopping cart full of items, and the cashier is looping through them one at a time:

for eachitem in mybasket: 
    # add item to total
    # go to next item.

If mybasket were actually a bag of apples, then eachitem that is in mybasket would be an individual apple; but if mybasket is actually a shopping cart, then the entire bag could itself meaningfully be a single "item".

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
beroe
  • 11,784
  • 5
  • 34
  • 79
  • It's important to understand that the loop **assigns to** whatever is put between `for` and `in`, just like if you used `=`. It's possible (although very much not recommended) to, for example, use an element in an existing list to store the iteration variable, like `for x[0] in y:`, which will replace the `[0]` element of `x` with a new element from `y` each time. – Karl Knechtel Jul 30 '22 at 02:26
  • Less obscurely, we can use unpacking syntax between `for` and `in`, if we iterate over a sequence of iterables: `for x, y in [[1,2], [3,4]]` will mean that the first time through the loop, `x` is equal to `1` and `y` is equal to `2`; the second time through, `x` is equal to `3` and `y` is equal to `4`. See also: https://stackoverflow.com/questions/7463683 – Karl Knechtel Jul 30 '22 at 02:29
  • It's also important to understand that whatever is assigned here, *doesn't need to have existed before*. Some beginners are confused by `for eachitem in mybasket:` if/because there was no previous `eachitem` in the program. But, again - this is an **assignment**, and there is **nothing special** about the first time a value is assigned. Python does not have anything like variable initialization or declaration; if you want to assign something, you just do it. – Karl Knechtel Jan 25 '23 at 06:31
2

A for loop works on an iterable: i.e., an object that represents an ordered collection of other objects (it doesn't have to actually store them; but most kinds of iterable, called sequences, do). A string is an iterable:

>>> for c in "this is iterable":
...     print(c, end=" ")
...
t  h  i  s     i  s     i  t  e  r  a  b  l  e 

However, a number is not:

>>> for x in 3:
...     print("this is not")
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

The built-in range function allows an easy way to iterate over a range of numbers:

>>> for x in range(3):
...     print(x)
...
0
1
2

In 2.x, range simply creates a list with those integer values; in 3.x, it makes a special kind of object that calculates the numbers on demand when the for loop asks for them.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Freddie
  • 871
  • 6
  • 10
1

In simple terms, Python loops over an iterable object, such as a string, list or tuple. For a list, it will loop through the list elements:

>>> numbers = [1, 2, 3, 4, 5]
>>> for n in numbers: print(n)
1
2
3
4
5

For a string, it will loop through individual characters (technically, Unicode code points):

>>> my_happy_string = "cheese"
>>> for c in my_happy_string: print(c)
c
h
e
e
s
e

Here is another example with a list of words:

>>> list_of_words = ["hello", "cat", "world", "mouse"]
>>> for word in list_of_words: print(word)
hello
cat
world
mouse

If you want a for loop that would start at 0 and end at 10, you can use the built-in range function:

>>> for i in range(0, 10): print(i)
0
1
2
3
4
5
6
7
8
9
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Games Brainiac
  • 80,178
  • 33
  • 141
  • 199
-1

What you have is more like a foreach loop.

Maybe something like this:

input = raw_input("> ") #separate with spaces
sum = 0
numbers = [int(n) for n in input.split()]
for number in numbers:
    sum = sum + number
print sum
John
  • 15,990
  • 10
  • 70
  • 110
  • 1
    Or: `sum(int(n) for n in raw_input("> ").split())`. –  Oct 08 '13 at 20:52
  • @iCodez But how will I know if your compact Python is correct without the `print` statement? :) – John Oct 08 '13 at 21:01
  • LOL. I made that in the Python interpreter where you don't need `print`. :) –  Oct 08 '13 at 21:03
  • 2
    I'm not sure how this explanation is helpful. Python doesn't have a `foreach` loop. Python's `for` loop is _always_ the equivalent of a "foreach" in other languages, and it's certainly not more of a "foreach" in the OP's code than in yours. And I doubt a novice who doesn't understand `for` loops is going to be helped by knowing that some other languages call the same thing `foreach`. – abarnert Oct 08 '13 at 21:13