zoukankan      html  css  js  c++  java
  • 9、循环语句


    9.1、for循环:

    1、循环格式:

    for 变量名 in 字符串:

    变量名


    #可以使用break、continue参数

    #continue ,终止当前循环,开始下一次循环

    #break ,终止所有循环


    2、

    test = "妹子有种冲我来"

    index = 0

    while index < len(test):

    v = test[index]

    print(v)


    index += 1

    print('=======')


    for n in test:

    print(n)


    3、

    test = "妹子有种冲我来"

    for item in test:

    print(item)

    break


    for item in test:

    continue

    print(item)


    4、获取连续或不连续的数字:

    #Python2中直接创建在内容中

    #python3中只有for循环时,才一个一个创建

    r1 = range(10)

    #0-9

    r2 = range(1,10)

    #1-9

    r3 = range(1,10,2)

    #1 1+2 3+2 5+2 7+2

    帮助创建连续的数字,通过设置步长来指定不连续


    for item in r1:

    print(item)


    5、根据用户输入的值,输出每一个字符以及当前字符所在的索引位置:

    v = input("<<<")

    for item in range(0,len(v)):

    print(item,v[item])


    9.2、while循环:

    1、死循环

    while 1==1:

    print('ok')


    2、使用while循环输入 1 2 3 4 5 6 8 9 10:

    n = 1

    while n < 11:

    if n == 7:

    pass

    else:

    print(n)

    n = n + 1

    print('----end----')

    3、求1-100的所有数的和:

    n = 1

    s = 0

    while n < 101:

    s = s + n

    n = n + 1

    print(s)


    4、输出 1-100 内的所有奇数:

    n = 1

    while n < 101:

    temp = n % 2

    if temp == 0:

    pass

    else:

    print(n)

    n = n + 1

    print('----end----')

    5、输出 1-100 内的所有偶数:

    n = 1

    while n < 101:

    temp = n % 2

    if temp == 0:

    print(n)

    else:

    pass

    n = n + 1

    print('----end----')


    6、求1-2+3-4+5 ... 99的所有数的和:

    n = 1

    s = 0

    #s是之前所有数的总和

    while n < 100:

    temp = n % 2

    if temp == 0:

    s = s - n

    else:

    s = s + n

    n = n + 1

    print(s)











  • 相关阅读:
    macOS免费的NTFS读写软件
    Python模块和模块引用(一)
    Python Class (一)
    Ubuntu系统管理systemd
    Case Closed?
    The 'with' and 'as' Keywords
    Buffering Data
    rstrip
    堆排序
    堆 续9
  • 原文地址:https://www.cnblogs.com/LiuChang-blog/p/12317190.html
Copyright © 2011-2022 走看看