• 7--Python入门--条件和循环


    5.1 条件语句

    条件语句基本框架如下:
    if 判断语句1:
       执行语句块1
    elif 判断语句2:
       执行语句块2
    else:
       执行语句块3

    a = 10
    if a%2 == 0 :     #这里使用了取余函数%
        print(a,'是偶数')
    else:
        print(a,'是奇数')
    View Code

    输出:10 是偶数

    b = '张三'
    if b in ['张一','张二','张三','张四']:  #这里使用了in来判断
        print(b,'是张家人')
    else:
        print(b,'不是张家人')
    View Code

    输出:张三 是张家人

    c = 20
    if c < 20:
        print(c,'小于20')
    elif c > 80:
        print(c,'大于80')
    else:
        print(c,'在20~80之间')
    View Code

    输出:20 在20~80之间

    5.2 循环语句

    5.2.1 for循环

     
    sum = 0  #实现0+1+2+。。+9
    for j in range(10):
        sum = sum + j
    print(sum)
    View Code

    输出:45

    5.2.2 while循环

    j = 1
    while j != 6:
        j = j + 1
    print('循环结果为:',j)
    View Code

    输出:循环结果为: 6

    5.2.3 循环控制语句——break

    break语句的含义是终止当前循环,且跳出整个循环

    for j in range(10):
        if j == 6:
            break
        print('当前j的值为:',j)
    View Code

    输出:

    当前j的值为: 0
    当前j的值为: 1
    当前j的值为: 2
    当前j的值为: 3
    当前j的值为: 4
    当前j的值为: 5

    5.2.4 循环控制语句——continue

    continue语句的含义是终止当次循环,跳出该次循环,直接执行下一次循环

     
    for j in range(10):
        if j == 6:
            continue
        print('当前j的值为:',j)
    View Code
    输出:
    当前j的值为: 0 当前j的值为: 1 当前j的值为: 2 当前j的值为: 3 当前j的值为: 4 当前j的值为: 5 当前j的值为: 7 当前j的值为: 8 当前j的值为: 9

    5.2.5 pass语句

    当执行到pass语句时,其含义就是不执行任何操作

     
    for j in range(10):
        if j == 6:
            pass
        else:
            print('当前j的值为:',j)
    View Code

    输出:

    当前j的值为: 0
    当前j的值为: 1
    当前j的值为: 2
    当前j的值为: 3
    当前j的值为: 4
    当前j的值为: 5
    当前j的值为: 7
    当前j的值为: 8
    当前j的值为: 9

    5.2.6 循环、条件嵌套

     例如我们要寻找2-100中的所有素数,本身需要一个循环。而判断某一个数是否为素数也需要一个循环,所以这里嵌套了两个循环。循环中还有一些条件语句。

     素数曾称质数。一个大于1的正整数,如果除了1和它本身以外,不能被其他正整数整除,就叫素数。如2,3,5,7,11,13,17…。
     
    #寻找2-100中的所有素数
    num = []  #这里创建一个空列表是为了存储结果
    for i in range(2,100):
        j = 2
        while j <= i/j : 
            if i%j == 0: #%指计算余数
                break
            j = j + 1
        if j > i/j:
            num.append(i)
    print(num)
    View Code

    输出:

    [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
    
     
  • 相关阅读:
    brew一直卡在Updating Homebrew的解决办法
    ELK5.6.4+Redis+Filebeat+Nginx(CentOS7.4)
    CentOS7.3 ffmpeg安装
    nginx Dockerfile
    pip安装第三方包超时
    logrotate nginx日志切割
    Ansible部署zabbix-agent
    Zabbix主动模式和被动模式
    Zabbix添加监控主机
    Zabbix3.2安装
  • 原文地址:https://www.cnblogs.com/lizhiyan/p/9712163.html
Copyright © 2020-2023  润新知