习题30:While循环

发布时间:2017-11-20 16:20:55编辑:Run阅读(5546)

    while循环有一个问题,那就是有时它永不结束,不过在其它的情况下你的循环总需要有一个结束点

    为了避免这样的问题,你需要遵守下面的规定:

    1.尽量少用while-loop,大部分时候for-loop是更好的选择

    2.重复检查你的while语句,确定你测试的布尔表达式最终会变成False

    3.如果不确定,就在while-loop的结尾打印出你要测试的值

    练习代码如下

    # coding: utf-8
    __author__ = 'www.py3study.com'
    i = 0
    numbers = []
    while i < 6:
       print("At the top i is {}".format(i))
       numbers.append(i)
       i = i + 1
       print("Numbers now:", numbers)
       print("At the bottom i is {}".format(i))

    print("The numbers:")
    for num in numbers:
       print(num)

    应该看到的结果

    图片.png

    常见问题

    for-loop和while-loop有何不同?

    for-loop只能对一些东西的集合进行循环,而while-loop可以对任何对象进行循环


关键字