zoukankan      html  css  js  c++  java
  • Python3练习题系列(03)

    题目:

    思考While循环,看看它的特点是什么?

    知识点:

    while循环

    分析:

    特点:while-loop(while 循环)。while-loop 会一直执行它下面的代码片段,直到它对应的布尔表达式为False 时才会停下来。

    问题:while循环的条件总是为真时,该循环永不停止,直到天荒地老,海枯石烂。

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

    1. 尽量少用while-loop,大部分时候for-loop 是更好的选择。
    2. 重复检查你的while 语句,确定你测试的布尔表达式最终会变成False 。
    3. 如果不确定,就在while-loop 的结尾打印出你要测试的值。看看它的变化。

    代码分析:

    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, end='	')

    结果:

    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

    来自《笨办法学Python》
  • 相关阅读:
    java 求 1!+2!+3!+....+10!的和为
    Java 循环控制语句
    java for 循环 九九乘法表
    Java for 循环
    Java while 和 do...while
    Java if语句
    Java switch 语句
    java a++ 和 ++a 理解
    Java 自动转换和强制转换
    二叉树遍历
  • 原文地址:https://www.cnblogs.com/brightyuxl/p/9189139.html
Copyright © 2011-2022 走看看