趣学Python第6章whlie
for循环用于指定长度的循环,whlie用于事先不知道什么时候停止的情况
step = 0
while step < 100000:
print(step)
step = 2**step
=================== RESTART: C:\Python27\lianxi\2018123.py ===================
0
1
2
4
16
65536
x = 45
y = 80
while x < 50 and y < 100:
print (x,y)
x = x + 1
y = y + 1
=================== RESTART: C:\Python27\lianxi\2018123.py ===================
(45, 80)
(46, 81)
(47, 82)
(48, 83)
(49, 84)
可以使用break跳出循环
6.4的练习
1.打印一次,退出
for x in xrange(1,20):
print('hello %s'%x)
if x<9:
break
=================== RESTART: C:\Python27\lianxi\2018123.py ===================
hello 1
2.
for x in xrange(1,38+1):
if x % 2 ==0:
print x
else:
pass
ok
3.
favgame=['read','program','write','dumping','bread','fruit']
for x in favgame:
print (x)
=================== RESTART: C:\Python27\lianxi\2018123.py ===================
read
program
write
dumping
bread
fruit
>>>
weight =50
x=1
while x < 16:
y =weight+x
monweight =y*0.165
print('第%s年过去的体重是%f,月球的体重是%f' %(x,y,monweight))
x= x+1
=================== RESTART: C:\Python27\lianxi\2018123.py ===================
第1年过去的体重是51.000000,月球的体重是8.415000
第2年过去的体重是52.000000,月球的体重是8.580000
第3年过去的体重是53.000000,月球的体重是8.745000
第4年过去的体重是54.000000,月球的体重是8.910000
第5年过去的体重是55.000000,月球的体重是9.075000
第6年过去的体重是56.000000,月球的体重是9.240000
第7年过去的体重是57.000000,月球的体重是9.405000
第8年过去的体重是58.000000,月球的体重是9.570000
第9年过去的体重是59.000000,月球的体重是9.735000
第10年过去的体重是60.000000,月球的体重是9.900000
第11年过去的体重是61.000000,月球的体重是10.065000
第12年过去的体重是62.000000,月球的体重是10.230000
第13年过去的体重是63.000000,月球的体重是10.395000
第14年过去的体重是64.000000,月球的体重是10.560000
第15年过去的体重是65.000000,月球的体重是10.725000
weight =50
for x in xrange(1,16):
y =weight+x
monweight =y*0.165
print('第%s年过去的体重是%f,月球的体重是%f' %(x,y,monweight))
结果相同,其实for的确好写一些