python循环控制语句(for)

时间:2022-09-08 16:46:47
<span style="font-size:14px;"># -*- coding: cp936 -*-
#循环字符串
s1 = "Hello world!"
i = 0
for c in s1:
    print format(i,"2d"),c
    i = i + 1
else:
    print "out for!"

#循环列表 列表数据可修改
i = 0
list1 = [1,3,5,"nihao",10,18,14.5]
for val in list1:
    print format(i,"2d"),val
    i = i + 1

#字符串转换成列表
list2 = list(s1)
print list2

#range函数 从1到100 步长是2
listNum = range(1,100,2)
i = 0
for val in listNum:
    print format(i,"2d"),val
    i = i + 1

#tuples 元组 数据项不可修改
i = 0
tup1 = (1,3,5,"nihao",0,18,14.5)
for val in tup1:
    print format(i,"2d"),val
    i = i + 1
else:
    print "out tup"

#循环文件 files 读文件
for c in open("for.py","r").readline():
    print c,
else:
    print "out end line"

i = 0
fileLines = open("d:\pythonRead.txt","r").readlines()
for val in fileLines:
    print format(i,"2d"),val
    i = i + 1
else:
    print "out"

#写文件
fileLines = open("d:\pythonRead.txt","r").readlines()
for val in fileLines:
    open("d:\pythonWrite.txt","a+").write(val)
else:
    print "end"
    


</span>