• python基础之循环


    1.while循环:

    使用场景:当不确定循环次数的时候

    注:一定要避免死循环

     

     while单独使用

    #常规的while循环:
    count = 0
    while (count < 3):   #循环判断
        print( 'The count is:', count)
        count = count + 1
    print("结束")
    
    #运行结果为:
    The count is: 0
    The count is: 1
    The count is: 2
    结束

    while中continue使用

    count = 0
    while (count < 4):   #循环判断
        count = count + 1
        if count == 2:
            continue           #结束本次循环
        print("这次输出",count)
    print("结束")
    
    #运行结果为:
    这次输出 1
    这次输出 3
    这次输出 4
    结束

    while中break使用

    count = 0
    while (count < 4):   #循环判断
        count = count + 1
        if count == 2:
            break      #结束循环
        print("这次输出",count)
    print("结束")
    
    #运行结果为:
    这次输出 1
    结束

    2.for循环使用:

    应用场景:循环次数确定

    遍历对象:for in 列表/字典/元组/字符串

    遍历列表的值:

    weekdays = ["","","","",""]
    #遍历值
    for i in weekdays:
        print(f"星期{i}")
    
    #运行结果为:
    星期一
    星期二
    星期三
    星期四
    星期五

    遍历字典的值

    a = {"name":"chenran","city":20,"爱好":"篮球"}
    for key,value in a.items():   #遍历字典的key,value
        print(key,value)
    #运行结果为:
    name chenran
    city 20
    爱好 篮球
    b =[("friends","小名"),("sex",""),("爱好","篮球")]
    for key,value in b:
        print(key, value)
    #运行结果为:
    friends 小名
    sex 男
    爱好 篮球

    3.双重for循环:

    persons = ["chenran","dalao","tingting"]
    foods = ["","大虾","青菜","牛肉","玉米"]
    for person in persons:  #遍历人
        print(f"当前取餐人{person}")  #换行
        for food in foods: #遍历食物
            print(f"拿取的食物是{food}",end=" ")
    
    #运行的结果为:
    当前取餐人chenran
    拿取的食物是鱼 拿取的食物是大虾 拿取的食物是青菜 拿取的食物是牛肉 拿取的食物是玉米 当前取餐人dalao
    拿取的食物是鱼 拿取的食物是大虾 拿取的食物是青菜 拿取的食物是牛肉 拿取的食物是玉米 当前取餐人tingting
    拿取的食物是鱼 拿取的食物是大虾 拿取的食物是青菜 拿取的食物是牛肉 拿取的食物是玉米 

    九九乘法表:

    for a in range(1,10):
        for b in range(1,10):
            if a >= b:
                print(f"{a}*{b}={a*b}",end=" ")  #每行输出,加空格
        print()  #b输完了换行
    
    #运行结果为:
    1*1=1 
    2*1=2 2*2=4 
    3*1=3 3*2=6 3*3=9 
    4*1=4 4*2=8 4*3=12 4*4=16 
    5*1=5 5*2=10 5*3=15 5*4=20 5*5=25 
    6*1=6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36 
    7*1=7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49 
    8*1=8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64 
    9*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81 
  • 相关阅读:
    request和request.form和request.querystring的区别
    VS2010中如何创建一个WCF
    ASP.Net MVC 3.0 之 MVCContrib的使用
    C# 请假小时数的计算(完整代码)
    C#调用WebService
    .Net Framework 框架工作原理
    做程序员的感悟
    WCF入门简单教程(图文) VS2010版
    仿淘宝的浮动工具栏(兼容IE6和其他浏览器)
    (原创)LINQ To SQL简单入门
  • 原文地址:https://www.cnblogs.com/crdhm12040605/p/15106465.html
Copyright © 2020-2023  润新知