内容正文:
《Python应用程序设计》
Python for循环结构
计算机教科组
1
for循环格式
序列包括:字符串、列表、元组、字典、集合、文件、range( )函数等
for循环是在遍历结构的序列穷尽时结束循环,而while循环是在条件不成立时结束循环。
遍历列表
for i in ['P', 'y', 't', 'h', 'o', 'n']:
print(i)]
运行结果:
P
y
t
h
o
n
for i in range(1,5):
print(i)
运行结果:
1
2
3
4
遍历元组
for i in (1,2,3):
print(i)
运行结果:
1
2
3
遍历字典:默认遍历字典的键
d={'name':'zhangsan','age':18,'sex':'男'}
for i in d:
print(i)
运行结果:
name
age
sex
遍历字典的值
d={'name':'zhangsan','age':18,'sex':'男'}
for i in d.values():
print(i)
运行结果:
zhangsan
18
男
遍历字典所有的键值对
d={'name':'zhangsan','age':18,'sex':'男'}
for i in d.items():
print(i)
运行结果:
('name', 'zhangsan')
('age', 18)
('sex', '男')
遍历集合
s={'apple', 'orange', 'pear'}
for i in s:
print(i)
运行结果:
orange
apple
pear
for循环例题
例1:以下程序的运行结果是( )。
s="abcd"
for i in range(len(s)):
print(s[-i],end="")
A.abcd B.bcda C.dcba D.adcb
答:D
len(s)=4;i可取值为0,1,2,3
i=0,s[0]='a'
i=1,s[-1]='d'
i=2,s[-2]='c'
i=3,s[-3]='b'
for循环例题
例2:以下程序的运行结果是( )
for i in (1,5):
a=i*2
print(a,end="\t")
A.2 4 6 8 B.2 4 6 8 10 C.2 10 D.2 4 6 8 t
例3:以下程序的运行结果是( )
for i in range(1,5):
a=i*2
print(a,end="\t")
A.2 4 6 8 B.2 4 6 8 10 C.2 10 D.2 4 6 8 t
for循环例题
例4:以下程序的运行结果是
list1=[1,2,3]
list2=['a','b','c']
d={}
for i in range(len(list1)):
d[list1[i]]=list2[i]
print(d)
for循环经典例题
[例1]for循环完成5遍“computer"输出
for i in range(5):
print("computer")
运行结果:
computer
computer
computer
computer
computer
for循环经典例题
[例2]使用 for语句循环求1+2+3+...+100的和。。
s=0
for i in range(1,101):
s=s+i
print("1+2+3+...+100="+str(s))
for循环经典例题
[例3]用for循环编写程序,利用循环求1-2+3-4+5…+99-100的值
方法一:判断每一行是奇数还是偶数,奇数则做加法,偶数则做减法
s=0
for i in range(1,101):
if i%2==1:
s+=i
else:
s-=i
print(s)
for循环经典例题
[例3]用for循环编写程序,利用循环求1-2+3-4+5…+99-100的值
方法二:
s=0;f=1
for i in range(1,101):
s+=i*f
f=-f
print(s)
请思考:1-1/2+1/3-1/4+...+1/99-1/100的值,结果保留到小数点后两位。
THANK YOU
16
$