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
    长得丑就应该多读书。我爱学习,只爱学习,最爱学习!
  • 相关阅读:
    生命的等级
    一个笑话
    第一天的日记
    接吻鱼的秘密
    [转载] 女人到底想要什么??
    纪念一塌糊涂bbs
    上海市区找到一处比较便宜的打乒乓地方:)
    朋友在奔驰公司,给我提供的F1照片,奔驰必胜!
    前台mm何处有?
    一个令我感动的女孩!
  • 原文地址:https://www.cnblogs.com/xc-718/p/9642839.html
Copyright © 2011-2022 走看看