zoukankan      html  css  js  c++  java
  • Python——while、continue、break、while-else、or、and、not

    1. while

      终止while循环:
        (1) 改变条件,使其不成立
        (2) break

      应用实例1:计算1+2+3+...+100

    #1.使用两个变量
    count = 1
    sum = 0
    while count <= 100:
        sum = sum + count
        count = count + 1
    print(sum)  #5050
    #2.使用三个变量
    count = 1
    sum = 0
    flag = True
    while flag:
        sum = sum + count
        count = count + 1
        if count > 100:
            flag = False
    print(sum)

      应用实例2:打印1-100

    #1.使用两个变量
    count = 1
    flag = True
    while flag:
        print(count)
        count = count + 1
        if count > 100:
            flag = False
    
    #2.使用一个变量
    count = 0
    while count <= 100:
        print(count)
        count = count + 1

    2. continue

      结束本次循环,继续下一次循环

    #一直循环输出1
    count = 1 while count < 20: print(count) continue count = count + 1  

    3. break

    print('11')
    while True:
        print('222')
        print(333)
        break
        print(444)
    print('abc'

      应用实例:打印1-100

    count = 1
    while True:
        print(count)
        count = count + 1
        if count > 100:break

    4. while-else

      (1)while循环被break打断,则不执行else
      (2)while循环未被break打断,则执行else

    count = 0
    while count <= 5:
        count += 1
        if count == 3:
            break  #(1)不执行else,如下左图
            #pass  #(2)执行else,如下右图
        print('loop',count)
    else:
        print('循环正常执行结束')

    5. 逻辑运算符or_and_not

    (1)x or y

      若x为真,返回x(0为假,其余为真);否则返回y

    print(1 or 2)   #1
    print(1 or 5)   #1
    print(0 or 1)   #1
    print(0 or 2)   #2

    (2)x and y(结果与or相反)

       若x为真,返回y(0为假,其余为真);否则返回x

    print(1 and 2)   #2
    print(1 and 5)   #5
    print(0 and 1)   #0
    print(0 and 2)   #0

    (3)not x

      若x为真,返回True;否则返回False

    print(not 0)    #True
    print(not 1)    #False
    print(not 56)   #False
    长得丑就应该多读书。我爱学习,只爱学习,最爱学习!
  • 相关阅读:
    DirectUI精髓之一 控件布局的自动缩放(弹簧特性)
    windows mobile6.5截屏工具
    实现的ATL(AtlSimpleArray)数组任意插入辅助函数
    动态库中单例一记
    ASP.NET组件设计Step by Step(4)
    Asp.net 中服务端控件事件是如何触发的
    PagesSection.EnableEventValidation 属性
    ASP.NET事件回传机制
    (服务器控件)页面框架处理回发数据的过程
    ASP.NET底层架构
  • 原文地址:https://www.cnblogs.com/xc-718/p/9642839.html
Copyright © 2011-2022 走看看