TheforstatementinPythondiffersabitfromwhatyoumaybeusedtoinCorPascal.Ratherthanalwaysiteratingoveranarithmeticprogressionofnumbers(likeinPascal),orgivingtheusertheabilitytodefineboththeiterationstepandhaltingcondition(asC),Python’sforstatementiteratesovertheitemsofanysequence(alistorastring),intheorderthattheyappearinthesequence.Forexample(nopunintended):Python中的for语句与C或PASCAL中使用的不同。而不是总是在算术级数(例如PASCAL)上迭代,或者给用户定义迭代步骤和停止条件(如C)的能力,Python中for语句在任意序列(列表或字符串)的项上迭代,按照它们所提出的顺序。序列中的R。例如(没有双关语):
#Measuresomestrings:测量字符串长度(例子)
...words=[cat,window,defenestrate]#创建一个列表
forwinwords:
...print(w,len(w))
...
cat3
window6
defenestrate12
Ifyouneedtomodifythesequenceyouareiteratingoverwhileinsidetheloop(forexampletoduplicateselecteditems),itisre