zoukankan      html  css  js  c++  java
  • 7.12_python_lx_day6

    一.关键字的使用 pass  break  continue

    <1>pass 过(占位)

    if 10 == 10:
      print(123)

    while True:
      pass

    <2>break 终止当前循环

     ①打印1~10 遇到5就终止循环

    i = 1
    while i <=10 :
      if i == 5:
        break
      print(i)
      i+=1

    ②break 终止的是当前循环

    i = 1
    while i <= 3:
      j = 1
      while j<=3:
        if j == 2:
          break
        print(i,j)
        j+=1
      i+=1

    <3>continue 跳过当前循环,从下一次循环开始

    ①打印1~10 跳过5

    i = 1
    while i<=10:
    	if i == 5:
    	  # 需手动自增加1. 当执行continue时,后面的代码不执行,跳到while循环的条件判断处,会造成死循环
    	  i+=1
    	  continue
    	print(i)
    	i+=1
    

    ②打印1~ 100 所有不含有4的数字

    方法一:

    i = 1
    while i<=100:
    	if i // 10 == 4 or i % 10 == 4:
    	  i+=1
    	  continue
    	print(i)
    	i+=1
    

    方法二:

    i = 1
    while i <= 100:
    	strvar = str(i)
    	if "4" in strvar:
    	  i+=1
    	  continue
    	print(i)
    	i+=1
    

    二.for循环 

    <1>遍历,循环,迭代

    lst = ["aaa","bbb","ccc","ddd"]
    i = 0
    while i<len(lst):
      # 代码的逻辑
      print(lst[i])
      i+=1
    

     for主要用于遍历数据而提出,while在遍历数据时,有局限性

    for 变量 in 可迭代对象:
    code1
    code2
    可迭代对象(容器类型数据,range对象,迭代器)

    # 遍历字符串
    container = "aaa,bbb,ccc"
    # 遍历列表
    container = ["ddd","eee","fff","hhh"]
    # 遍历元组
    container = (1,2,3,45)
    # 遍历集合
    container = {"iii","jjj","kkk","lll","mmm"}
    # 遍历字典 (遍历字典时,只遍历键)
    container = {"a":1,"b":2,"c":3}

    for i in container:
      print(i)

    <2>遍历不等长的二级容器

    container = [["aa","bb","cc","dd"],("ee","ff")]
    for i in container:
      # print(i)
      for j in i:
        print(j)
    

    <3>遍历等长的二级容器

    container = [("ab","ac","ad") , ("ef","eg","eh") , ("ij","ik","il") ]
    for x,y,z in container:
      print(a,b,c)
    # x,y,z = ("ab","ac","ad")
    # x,y,z= ("ef","eg","eh")
    # x,y,z = ("ij","ik","il")

    <4>range对象

    range(开始值,结束值,步长)
    结束值本身取不到,取到结束值之前的那个数

    ①只有一个值  0~9

    for i in range(10):
      print(i)

    ②只有两个值

    for i in range(3,11):
      print(i)

    ③只有三个值

    for i in range(1,10,3):
      print(i)

    ④倒序打印10 ~ 1

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

    三:总结

    while : 较为复杂的逻辑
    for : 数据的遍历
    while 和 for 部分代码可以互相转换

  • 相关阅读:
    ZOJ 1002 Fire Net (火力网)
    UVa OJ 117 The Postal Worker Rings Once (让邮差只走一圈)
    UVa OJ 118 Mutant Flatworld Explorers (变体扁平世界探索器)
    UVa OJ 103 Stacking Boxes (嵌套盒子)
    UVa OJ 110 MetaLoopless Sorts (无循环元排序)
    第一次遇到使用NSNull的场景
    NSURL使用浅析
    从CNTV下载《小小智慧树》
    NSDictionary and NSMutableDictionary
    Category in static library
  • 原文地址:https://www.cnblogs.com/Magicianlx/p/13288759.html
Copyright © 2011-2022 走看看