简体   繁体   中英

Understanding for loops in Python

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

For loops take each item in a thing , assign that value to a variable like w or number , do an operation, and then move on to the next item until they run out.

Let's get your example working first...

numberstring = raw_input("> ")  # expect a string like "1 2.0 4 100"
addition = 0
numberlist = numberstring.split(" ") # convert the chars into a list of "words"
for number in numberlist:
    addition = addition + float(number)
print addition

Without coverting to a list using .split() , your loop will move through each letter of the string, interpreting it as a letter instead of a number. And without converting those words as numbers (using float() ) it could even add the string back together (except in this case there has been an initialization with zero).

One source of confusion on lists: the NAME of the variable doesn't matter. If you say for letter in myvar: it doesn't force the program to choose letters. It just takes the next item and assigns that value to the variable letter . In Python this item can be a list of words, numbers, etc, or if given a string, it will take characters as the items.

Another way to envision it is that you have a shopping basket 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 you handed them a bag of apples and asked them to loop through it, they would take out each apple, but if you give them a basket, they will take the bag out as one item...

Well, a small console session should clear this up. In simple terms, Python loops over an iterable object. Now what does this mean. It means thats like strings, like lists or arrays.

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

Basically, it will loop through anything it can loop through. Here is another example:

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

Here is an 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

Basically, python needs objects that it can loop through to make a for loop, so if you wanted a for loop that would start at 0 and end at 10 , you would do something like this:

>>> for i in range(0, 10): print i
0
1
2
3
4
5
6
7
8
9

Lets take a look at what the range function returns:

>>> range(0, 10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Basically, it just returns a list. So, in simple terms, you need a list of something. Technically, a string is a list of characters stuck together.

Hope that helps.

For loops work on objects that are iterables (objects that are capable of returning their objects one at a time). A string is an iterable

>>> for c in "this is iterable":
...   print c + " ",
...
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

To iterate over a range of numbers, python gives you a nice generator function called... you guessed it, range which returns a list in Python 2.x.

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

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

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, eg, print w, len(w) prints both the word w and also its length. This will not work as stated in python 3 or later.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM