• python入门到放弃(二)-流程控制语句


    所谓流程控制,就是在程序里面设定一些条件判断语句,满足哪条,就执行哪条

    1.if

    单分支

    if 条件:
        满足条件后执行的代码
    
    #例子
    if 5 > 4 : print(666)
    #结果为
    666

    双分支

    if 条件:
        满足条件执行的代码
    else:
        if条件不满足执行的代码
    #例子
    if 6 > 5 : print(666) else: print(555)
    #执行结果为
    666

    多分支

    if 条件:
        满足条件执行的代码
    elif 条件:
        上面的条件不满足执行的代码
    elif 条件:
        上面的条件不满足执行的代码
    else:
        上面所有的条件不满足执行的代码
    
    #例子
    num = input('请输入你猜的数字:')
    
    if num == '1':
        print('一起去唱歌')
    elif num == '2':
        print('一起去跳舞')
    elif num == '3':
        print('一起去玩')
    else:
        print('回家睡觉')

    #提示:冒号是隔开条件和结果的标识符

    2.while

    语法

    while 条件:
        循环体
    while True:
        print('wo')
        print('he')
        print('ni')
    #这样会陷入无限循环

    终止循环

    #终止循环
        1、改变条件,使其不成立    
        2、break
        3、continue跳出循环
    
    count = 1
    flag = True
    while flag:
        print(count)
        break
    #结果
    1
    count
    = 1 flag = True while flag: print(count) count = count + 1 if count > 100 : flag = False
    #当count大于100的时候,就设置成False,使其不成立
    count
    = 0 while count <=100: count = count + 1 if count > 5 and count < 95: continue print("loop", count)
    #当执行count大于5和小于95的时候就跳出循环,不执行

    while ..else

    #while语句被break终止的时候else就不会执行,没有被break打断的时候就执行else语句
    count = 0
    while count <= 5:
        count += 1
        if count == 3:break
        print("Loop",count)
    else:
        print('循环正常执行完')
    print("----out of while loop ------")
    #执行结果:当count等于3的时候就break掉了,也不会打印else
    Loop 1 Loop 2 ----out of while loop ------

    count = 0 while count <= 5: count += 1 if count == 3:pass #允许通过就执行else print("Loop",count) else: print('循环正常执行完') print("----out of while loop ------")

    #执行结果:pass的时候就不做什么动作
    Loop 1 Loop 2 Loop 3 Loop 4 Loop 5 Loop 6 循环正常执行完 ----out of while loop ------

    3.for

    #简述

    可以使用for循环来获取字符串中的每一个字符

    #语法:

    for 迭代变量 in 可迭代对象(字符串|列表|元组|字典|集合):
        代码

    #扩展:可迭代对象:可以一个一个往外取值的对象。

    #例1:循环元组

    name = '1','2', '3','4'
    for shuzi in name:
         print(shuzi)
    #执行结果
    1
    2
    3
    4

    #例二:使用range()函数,迭代2-10的数字

    for a in range(2,10):
        print(a)
    #执行结果
    2
    ...
    10

    #例三:使用for ... else,如果for循环被break中断之后就不会执行else,如果没有中断就执行

    for a in range(1,5):
        if a % 2 == 0 :
            print(a)
    else:
        print('fd')
    #执行的结果为
    2
    4
    fd

    #python代码缩进的几个原则

      1、顶级代码必须顶行写

      2、同一级别的代码,缩进必须一致,否则执行会有问题

  • 相关阅读:
    一年三百六十日,需求业务严相逼
    新博客测试
    教务流水账
    暗流涌动的话“用户体验”
    文档那些事儿
    jforum(2)中文乱码的解决方式
    jmeter笔记(4)测试上传附件
    jmeter笔记(2)组件介绍
    jmeter笔记(5)参数化CSV Data Set Config
    jmeter笔记(6)参数化函数助手
  • 原文地址:https://www.cnblogs.com/guoke-boy/p/11746169.html
Copyright © 2020-2023  润新知