1.10 迭代与循环

1.10.1 for 与 range(i,j)
for n in range(1,10):
print (("2 to the %d power is %d") %(n, 2**n)) #2的n次方
输出结果:
2 to the 1 power is 2
2 to the 2 power is 4
2 to the 3 power is 8
2 to the 4 power is 16
2 to the 5 power is 32
2 to the 6 power is 64
2 to the 7 power is 128
2 to the 8 power is 256
2 to the 9 power is 512
1.10.2 range(i,j,[,进步值])函数
  range(i,j,[,步进值])函数创建的对象表示值 i j 的整数。如果起始值被省略,则认为是0。第三个参数是可选的步进值。例如:
a = range(5)
b = range(1,8)
c = range(0,14,3)
d = range(8,1,-1)
for n in a:
print("a= %d " %n)
输出结果:
a= 0
a= 1
a= 2
a= 3
a= 4
for n in b:
print("b= %d " %n)
输出结果:
b= 1
b= 2
b= 3
b= 4
b= 5
b= 6
b= 7
for n in c:
print("c= %d " %n)
输出结果:
c= 0
c= 3
c= 6
c= 9
c= 12
for n in d:
print("d= %d " %n)
输出结果:
d= 8
d= 7
d= 6
1.10.3 字符串
a = "Hello World" #字符串
for c in a:
print(c) #输出每个字符
1.10.4 列表
b = ["Dave", "Mark", "Ann", "Phil"]#列表
for name in b:
print (name)
输出结果:
Dav
Mark
Ann
Phil
1.10.5字典
c = {'GOOG':490.10, 'IBM':91.50, 'AAPL':123.15}#字典
for key in c:
print (key, c[key])
输出结果:
('GOOG', 490.1)
('AAPL', 123.15)
('IBM', 91.5)
1.10.6 文件
"foo.txt"文件的内容:
liwen
123.89
124
f = open("foo.txt")
for line in f:
print (line,)
输出结果:
('liwen\n',)
('123.89\n',)
('124\n',)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhizhuxialiwen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值