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
    长得丑就应该多读书。我爱学习,只爱学习,最爱学习!
  • 相关阅读:
    iOS开发常见错误(转)
    SVN各种错误提示产生原因及处理方法大全(转)
    SVN常见问题(转)
    iPhone6 Plus、iPhone6、iPhone5S和之前版本真实分辨率
    各类 HTTP 返回状态代码详解(转)
    js:全局作用域和调整浏览器窗口大小
    python之制作模块
    python之模块time | strftime || 模块datetime | timedelta | 计算3天前的日期
    python之模块 sys | os
    python之正则表达式 | match | split | findall | sub替换 |
  • 原文地址:https://www.cnblogs.com/xc-718/p/9642839.html
Copyright © 2011-2022 走看看