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?.
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".
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With