python 笔记 While 循环 《笨办法学Python》习题33 ——1.7

本文记录了学习《笨办法学Python》中关于While循环的练习,通过示例解析了while循环的工作原理,强调了可能导致无限循环的风险,并提供了两个示例程序的运行结果分析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

习题 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)


运行结果:





评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值