习题 33: While 循环
目标与感悟:
• while循环,中文翻译过来就是当….时,对于for的直到对应的是一个集合,很明显,while的界限更大,其可能无限循环,感觉其难度更高
• 例:
#-*-coding:utf-8-*-
i =2
while i <5:
print" hei hei hei "
i = i +1
print"\t\tOver!"
可知应该会输出" hei hei hei " 3次
• while 可能无限循环,所以使用要注意
例:
#-*-coding:utf-8-*-
i = 2
while i < i + 1:
print " hei hei hei "
i = i +1
print "\t\tOver!"
ex33.py
#-*-coding: utf-8-*-
#首先描述下脚本的功能:
#while循环:设定一个变量i,初始值为0;再设一个列表number,当前无值
# 当i小于6时,打印当前初始值,之后将i值赋值进列表number
# 之后将i值加1并打印当前列表number中的数
# 一直到 i < 6为False,循环结束
#此时进入一个for循环,将列表number赋值给num,打印num.
i = 0
numbers = []
while i < 6 :
print "At the top i is %d" % i
numbers.append(i)
i = i + 1
print "Number now: ", numbers
print "At the bottom i is %d" %i
print "The numbers: "
for num in numbers:
print "%s" % num
运行结果:
结合函数
ex33_1.py
#-*-coding: utf-8-*-
def test(n):
i = 1
list = []
while i < n:
print "Top,i is %s.\n i is smaller than %s" %(i,n)
list.append(i)
i = i + 2
print "Number now: %d" %i
print "At the bottom i is %d " % i
print "The list: "
for num in list:
print num
n = int(raw_input("Pleaes input a number:"))
test(n)
运行结果: