zoukankan      html  css  js  c++  java
  • 6流程控制-while

    二、循环语句


    当我们需要多次执行一个代码语句或代码块时,可以使用循环语句。Python中提供的循环语句有:while循环和for循环。需要注意的是Python中没有do..while循环。此外,还有几个用于控制循环执行过程的循环控制语句:break、continue和pass。

    1. while循环

    基本形式

    while循环语句的基本形式如下:

    while 判断条件:
        代码块

    当给定的判断条件的返回值的真值测试结果为True时执行循环体的代码,否则退出循环体。

    实例:循环打印数字0-9

    count = 0
    while count <= 9:
        print(count, end=' ')
        count += 1

    输出结果:0 1 2 3 4 5 6 7 8 9

    while死循环

    当while的判断条件一直为True时,while循环体中代码就会永远循环下去。

    while True:
        print("这是一个死循环")

    输出结果:

    这是一个死循环
    这是一个死循环
    这是一个死循环
    ...

    此时可以通过 Ctrl + C终止运行。

    while..else

    语句形式:

    while 判断条件:
        代码块
    else:
        代码块

    else中的代码块会在while循环正常执行完的情况下执行,如果while循环被break中断,else中的代码块不会执行。

    实例1:while循环正常执行结束的情况(else中的语句会被执行)

    count = 0
    while count <=9:
        print(count, end=' ')
        count += 1
    else:
        print('end')

    执行结果为:0 1 2 3 4 5 6 7 8 9 end

    实例2:while循环被中断的情况(else中的语句不会被执行)

    count = 0
    while count <=9:
        print(count, end=' ')
        if count == 5:
            break
        count += 1
    else:
        print('end')

    输出结果:0 1 2 3 4 5

  • 相关阅读:
    September 29th 2017 Week 39th Friday
    September 28th 2017 Week 39th Thursday
    September 27th 2017 Week 39th Wednesday
    September 26th 2017 Week 39th Tuesday
    September 25th 2017 Week 39th Monday
    September 24th 2017 Week 39th Sunday
    angular2 学习笔记 ( Form 表单 )
    angular2 学习笔记 ( Component 组件)
    angular2 学习笔记 ( Http 请求)
    angular2 学习笔记 ( Router 路由 )
  • 原文地址:https://www.cnblogs.com/wolfboy55-163-com/p/8128283.html
Copyright © 2011-2022 走看看