if判断、while循环、for循环

if

单独if

if 条件:
   结果

if else 二选一

if 条件:
   结果1
else:
   结果2

if elif elif .... 多选一

if 条件1:
   结果1
elif 条件2:
   结果2
elif 条件3:
   结果3
......

if elif elif .... else 多选一

if 条件1:
   结果1
elif 条件2:
   结果2
elif 条件3:
   结果3
......
else:
   结果N

嵌套的if

if 条件1:
   if 条件2:
   结果A
   else:
   结果B
else:
   结果C

 

while 循环

  • why:大气循环, 吃饭,上课,睡觉,日复一日,歌曲列表循序环,程序中:输入用户名密码,

  • what:while 无限循环。

  • how:

    1. 基本结构:

      while 条件:
         循环体
    2. 初识循环

      while True:
         print('狼的诱惑')
         print('我们不一样')
         print('月亮之上')
         print('庐州月')
         print('人间')
         
    3. 基本原理:

    4. 循环如何终止?

      1. 改变条件。

        flag = True
        while flag:
           print('狼的诱惑')
           print('我们不一样')
           print('月亮之上')
           flag = False
           print('庐州月')
           print('人间')
        # 练习题: 1~ 100 所有的数字
        count = 1
        flag = True
        while flag:
           print(count)
           count = count + 1
           if count == 101:
               flag = False
               
        count = 1
        while count < 101:
           print(count)
           count = count + 1
        # 1 + 2 + 3 + ...... 100  的最终结果:

        s = 0
        count = 1
        while count < 101:
           s = s + count
           count = count + 1
        print(s)
      1. break

      # while True:
      #     print('狼的诱惑')
      #     print('我们不一样')
      #     print('月亮之上')
      #     break
      #     print('庐州月')
      #     print('人间')
      # print(111)
      1. continue

        # continue : 退出本次循环,继续下一次循环
        flag = True
        while flag:
           print(111)
           print(222)
           flag = False
           continue
           print(333)
        # while else: while 循环如果被break打断,则不执行else语句。
        count = 1
        while count < 5:
           print(count)
           if count == 2:
               break
           count = count + 1
        else:
           print(666)
  • for(有限循环)

    for 变量 in iterable:
      pass
    s = '老男孩教育最好的讲师:太白'
    for i in s:
       print(i)
       
    输出结果:












    s = '老男孩教育最好的讲师:太白'
    for i in s:
       print(i)
       if i == '好':
           break

    输出结果:






    多重for循环中的break

    当多重for循环中有break时,仅跳出最内层的for循环

    for i in range(5):
      for j in range(5):
          print(i,j)
          if j==2:
              break
               
    输出结果:
    0 0
    0 1
    0 2
    1 0
    1 1
    1 2
    2 0
    2 1
    2 2
    3 0
    3 1
    3 2
    4 0
    4 1
    4 2

    for else

    用法与while else类似

猜你喜欢

转载自www.cnblogs.com/oddgod/p/10888765.html