一般形式
for <variable> in <sequence>:
<statements>
else:
<statements>
循環(huán)list
languages = ["C", "C++", "Perl", "Python"]
for x in languages:
print (x)
range()形式
>>>for i in range(5):
... print(i)
若指定步長(zhǎng)和區(qū)間
>>>for i in range(0, 10, 3) :
print(i)
range()與len()結(jié)合循環(huán)list(類似c循環(huán)情況)
>>>a = ['Google', 'Baidu', 'Runoob', 'Taobao', 'QQ']
>>> for i in range(len(a)):
... print(i, a[i])
冒泡排序
# python 冒泡排序
def paixu(li) :
max = 0
for ad in range(len(li) - 1):
for x in range(len(li) - 1 - ad):
if li[x] > li[x + 1]:
max = li[x]
li[x] = li[x + 1]
li[x + 1] = max
else:
max = li[x + 1]
print(li)