• ex33 while 循环


    1、再次注意;如果某行是以冒号结尾,则意味着接下来的内容是一个新的代码块,是要被缩进的。(在把while加入def的时候,def下一个缩进,while中又多一个缩进)

    2、while循环有可能会出现永不结束的状态。

    3、为了避免出现2中的问题,需要遵循以下规定:

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

    下边是练习代码以及附加练习的内容。

     1 #-*- coding: UTF-8 -*-
     2 #下面是最初的函数
     3 i = 0
     4 numbers = []
     5 
     6 while i < 6:
     7     print "At the top i is %d" % i
     8     numbers.append(i)
     9     
    10     i = i + 1
    11     print "Numbers now:", numbers
    12     print "At the bottom i is %d" % i 
    13 
    14     
    15 print "The numbers."
    16 
    17 for num in numbers:
    18     print num
    19     
    20 #将while循环改成了一个函数    
    21 def while_1(j,step):
    22     i = 0
    23     numbers = []
    24     while i < j:
    25         print "At the top i is %d " % i 
    26     
    27         numbers.append(i)
    28     
    29         i = i + step
    30         print "Numbers now:", numbers
    31         print "At the bottom i is %d" % i 
    32     
    33 result = while_1(20,1)
    34 
    35 
    36 #将函数中的while用for循环和range来代替。
    37 def for_range(j,step):
    38     i = 0
    39     numbers = []
    40     for i in range(0,j):
    41         print "At the top i is %d " % i 
    42     
    43         numbers.append(i)
    44     
    45         i = i + step#如果不去掉这一步,就只是在最后打印 at the bottom的时候加了一次,在循环中是不受影响的。
    46         print "Numbers now:", numbers
    47         print "At the bottom i is %d" % i
    48 result = for_range(20,2)

    常见问题回答

    1、for和while循环之间的区别:

    for循环只能对一些东西的集合进行循环,while循环可以对任何对象进行驯化。然而相比之下while比较容易出错,一般的任务还是用for循环更加容易一些。

  • 相关阅读:
    C#WinForm应用程序中嵌入ECharts图表
    C#自定义按钮、自定义WinForm无边框窗体、自定义MessageBox窗体
    C#自定义无边框MessageBox窗体
    C#自定义Winform无边框窗体
    C#自定义Button按钮控件
    C# 对象与JSON字符串互相转换的三种方式
    Spring.NET依赖注入框架学习--实例化容器常用方法
    Spring.NET依赖注入框架学习--简单对象注入
    Spring.NET依赖注入框架学习--简介
    Spring.NET依赖注入框架学习--入门
  • 原文地址:https://www.cnblogs.com/dingtou00/p/7800818.html
Copyright © 2020-2023  润新知