Understanding for loops in Python

Question:

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?

Asked By: musha1

||

Answers:

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
Answered By: John

There are two kinds of for loops.

What you are used to is probably:

sum = 0
for i in range(0,10):
    sum += 1
#prints 9

The syntax you have questioned is set notation. It says “for each member w of set words”, print w and the length of w. In python 2.7 and below, print can be used as a statement with multiple things to print, e.g, print w, len(w) prints both the word w and also its length. This will not work as stated in python 3 or later.

Answered By: Tommy

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".

Answered By: beroe

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.

Answered By: Freddie

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
Answered By: Games Brainiac
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.