Learn Python The Hard Way学习(33) - While循环

下面学习一个新的循环,while循环,如果while的布尔表达式一直是True,那么会不断的重复执行代码块。

等等,我们不是在学习一个新的术语吗?用冒号结束一行语句,然后开始新的代码段,使用缩进区别这些代码段,好吧,这就是python的语言结构,如果你还是很明白,回去多练习前面的for,if和函数。

后面我们会有一些练习让你记住这些结构,就像前面记住布尔表达式一样。

回到While循环,刚开始它和if一样,进入代码段执行,只是while循环执行完代码段后会回到这个代码段的顶部,重复执行,直到while的布尔判断为False为止。

这里有个问题:while循环有可能一直不会停止,不过你还是希望循环最终能够停止的。

为了解决这个问题,我们列出了一下规则:
  1. 不到万不得已不要使用while,可以用for代替。
  2. 仔细检查你的while声明,确保有条件让它返回False。
  3. 如果有怀疑的话,在代码段的头部和底部打印变量的值来判别。
下面看我是怎么做的:
i = 0
numbers = []


while i < 6:
    print "At the top i is %d" % i
    numbers.append(i)


    i = i + 1
    print "Numbers now: ", numbers
    print "At the bottom i is %d" % i


print "The numbers: "


for num in numbers:
    print num


运行结果
root@he-desktop:~/mystuff# python ex33.py 
At the top i is 0
Numbers now:  [0]
At the bottom i is 1
At the top i is 1
Numbers now:  [0, 1]
At the bottom i is 2
At the top i is 2
Numbers now:  [0, 1, 2]
At the bottom i is 3
At the top i is 3
Numbers now:  [0, 1, 2, 3]
At the bottom i is 4
At the top i is 4
Numbers now:  [0, 1, 2, 3, 4]
At the bottom i is 5
At the top i is 5
Numbers now:  [0, 1, 2, 3, 4, 5]
At the bottom i is 6
The numbers: 
0
1
2
3
4
5

加分练习
1. 把这个while循环写到一个函数中,用一个变量传递6这个值。
def while_function(i):
    j = 0
    numbers = []
    
    while j < i:
        numbers.append(j)
        j += 1


    return numbers


numbers = while_function(6)


2. 使用这个函数打印不同的数字。

3. 添加一个参数到函数中,让它可以根据这个参数修改增量值,就是i=i+1这里。
def while_function(i, increment):
    j = 0
    numbers = []
    
    while j < i:
        numbers.append(j)
        j += increment


    return numbers


numbers = while_function(6, 2)


4. 使用上面的函数运行一下。

5. 使用for循环和range函数实现上面的代码。
def for_function(i, increment):
    numbers = []
    for j in range(0, i, increment):
        numbers.append(j)
    return numbers


numbers = for_function(6, 2)


如果你调试代码的时候进入了无限循环,可以用ctrl+c退出。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值