码迷,mamicode.com
首页 > 其他好文 > 详细

Traversal with a for loop

时间:2014-06-23 07:19:02      阅读:257      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   http   tar   

A lot of computations involve processing a string one character at a time. Often they start at the beginning, select each character in turn, do something to it, and continue until the end. The pattern of processing is called traversal. One way to write a traversal is with a while statement:

index = 0
while index < len(fruit):
    letter = fruit[index]
    print letter
    index = index + 1

This loop traverses the string and displays each letter one a line by itself.
Another way to write a traversal is with a for loop:

for char in fruit:
    print char

Each time through the loop, the next character in the string is assigned to the variable char. The loop continues until no characters are left.
The following example shows how to use concatenation (string addition) and a for loop generate an abecedarian series (that is, in alphabetical order).

bubuko.com,布布扣

 

from Thinking in Python

 

 

Traversal with a for loop,布布扣,bubuko.com

Traversal with a for loop

标签:style   class   blog   code   http   tar   

原文地址:http://www.cnblogs.com/ryansunyu/p/3799591.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!