Python基础之流程控制-while循环与for循环

目录

一、while+continue

二、while+else

三、死循环

四、for循环

五、range关键字

六、for+break

七、for+continue

八、for+else

九、for循环的嵌套使用

 

一、while+continue

  continue:跳过本次循环,开始下一次循环

  # 打印从1-10
  count = 1
  while count < 11:
    print(count)
    count += 1


  # continue 跳过本次循环,执行下一次循环;continue 会让循环体代码直接回到条件判断处重新判断

  # 打印从1-10,跳过5
  # 定义起始变量
  count = 1
  # 循环
  while count < 11:
  # 当变量等于5
    if count == 5:
      count += 1
  # 直接跳过本次循环,开始下一次循环
      continue
  # 打印变量值
    print(count)
  # 变量值自增1
    count += 1

 

二、while+else

  else:while循环没有被人为中断(break)的情况下,会执行else

  # while+else:
    count = 1
    while count <6:
      print(count)
      count += 1
    else:
      print('嘿嘿嘿')
      count += 1

  # 被人为中断的情况下不执行else
  count = 1
  while count < 6:
    if count == 4:
      break
    print(count)
    count += 1

  else:
    print('嘿嘿嘿')

 

 

三、死循环

  会让CPU极度繁忙甚至崩溃,一直循环不会停下

    while True:
     print(1)

 

四、for循环

  for循环能实现的功能,while循环都能做到,但是for循环更简洁,并且在循环取值的问题上更方便。

  for循环的语法结构:for 变量名 in 可迭代对象:#字符串、列表、字典、元组、集合

  for 循环体代码

  ps:如果没有合适的变量名,可以使用i/j/k/v/item等等。

  1.for循环列表
  name_list = ['jason', 'tony', 'kevin', 'lili', 'body']
  # 用while循环实现
  count = 0
  while count < 5:
    print(name_list[count])
    count += 1

  # 用for循环实现
  for name in name_list:
    print(name)

  2.for循环字符串
  for i in 'hello':
    print(i)


  3.for循环字典:默认只能拿到K值
  d = {'username': 'jason', 'age': '18', 'height': '189'}
  for k in d:
    print(k, d[k])

 

 

   

 

 

 

 

 

 

五、range关键字

  # 第一种:一个参数,从0开始,顾头不顾尾
  for m in range(5):
    print(m)

  # 第二种:两个参数,自定义起始位置,顾头不顾尾
  for m in range(5, 8):
    print(m)

  # 第三种:三个参数,自定义起始位置,顾头不顾尾,第三个参数是控制等差值
  for m in range(2, 10, 2):
    print(m)

 

  # 在不同版本的解释器中,range本质不同
  在python2.X版本中,range会直接生成列表,xrange是一个迭代器(老母猪)
  在python3.X版本中,range是个迭代器(老母猪)
  '''可以理解为python2.X版本的xrange就是python3.X版本的range'''


  # 拓展知识 : %s:占位符
  base_url = "https://movie.douban.com/top250?start=%s&filter="
  for i in range(0, 250, 25):
    print(base_url % i) 

 

 

 

六、for+break

break功能也一样用于结束本层循环

  for m in range(20):
    if m == 3:
      break
    print(m)

 

七、for+continue

  continue功能也一样用于结束本层循环执行下一层循环

  for m in range(6):
    if m == 4:
      continue
    print(m)

 

 

 

八、for+else

  else也一样是for循环结束的情况下才会执行,如果被人为打断一样也不会执行

  for m in range(4):
    print(m)
  else:
    print('嘿嘿')

  # 当循环被人为中断,则不执行else
  for m in range(4):
    if m == 2:
      break
    print(m)
  else:
    print('嘿嘿')

 

 

 

九、for循环的嵌套使用

  for i in range(3):
    for j in range(5):
      print("*", end='')
    print()


  # 打印九九乘法表
  for i in range(1, 10):
    for j in range(1, i+1):
      print('%s*%s=%s' % (j, i, j*i), end=' ')
    print()

 

 

 

 

posted @ 2021-11-11 21:07  90啊  阅读(93)  评论(0编辑  收藏  举报