• Python06:for循环


    初识for循环:

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    #Author:Mclind

    for i in range(10):
        print ("loop", i)

    输出:

    loop 0

    loop 1

    loop 2

    loop 3

    loop 4

    loop 5

    loop 6

    loop 7

    loop 8

    loop 9

    Process finished with exit code 0

    解释:

    range(10)就相当于产生10个数字(0123456789

    猜数字用for循环实现:

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    #Author:Mclind

    age = 56

    for i in range(3):
        guess_age = int(input("guess age:"))
        if guess_age == age:
            print("yes, you got it.")
            break
        elif guess_age > age:
            print("think smaller...")
        else:
            print("think bigger...")
    else:
        print("you have tried too many times... fuck off")

    结果略,同while产生同样的效果,也可以接else,同while一样。

    for循环打印(设置步长):

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    #Author:Mclind

    for i in range(0,10,1):
        print("lo

    输出结果:

    loop 0

    loop 1

    loop 2

    loop 3

    loop 4

    loop 5

    loop 6

    loop 7

    loop 8

    loop 9

    Process finished with exit code 0

    for循环打印(设置步长):

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    #Author:Mclind

    for i in range(0,10,2):
        print("loop", i)

    输出结果:

    loop 0

    loop 2

    loop 4

    loop 6

    loop 8

    Process finished with exit code 0

    for循环打印(设置步长):

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    #Author:Mclind

    for i in range(0,10,3):
        print("loop", i)

    输出结果:

    loop 0

    loop 3

    loop 6

    loop 9

    Process finished with exit code 0

    解释:

    rangex,y,z):x起始值;

                 y:终止值;

                 z:步长。结合程序理解。

  • 相关阅读:
    SpringBoot整合Elasticsearch
    Elasticsearch环境搭建和介绍(Windows)
    Java并发AtomicBoolean类的使用
    RequestMapping详细用法
    RSA公钥加密 私钥解密
    java随机生成RSA密钥对
    java通过实体类生成数据库表 并生成注释
    设计模式-策略模式
    设计模式-模板方法模式使用
    设计模式-模板方法模式
  • 原文地址:https://www.cnblogs.com/mclind/p/8666144.html
Copyright © 2020-2023  润新知