Python循环语句


一.while循环

1.1基本格式:

      while 条件:

          如果条件成立之后循环执行的子代码块

1.2while+break循环语句

      while 条件:

         如果条件成立执行子代码块

         break(用于结束本层循环)

1.3while+continue循环语句

      continue会让循环体代码直接回到条件判断处重新判断,从而达到跳过某些内容的效果。例如:

# 使用while循环找出100以内的最大的6的倍数。
count = 100
while count > 0:
    if count % 6 == 0:
        print(count)
        break
    count -= 1

流程图如下:

# 使用while循环打印1到10,其中不含4
count = 0
while count < 11:
    if count == 4:
        count += 1
        continue
    print(count)
    count += 1

流程图如下:

 

1.4while+else循环语句

       当while循环没有被人为中断(break)的情况下才会走else代码块。

       简单的一个例子:

count = 0
while count < 5:
    print(count)
    count += 1
else:
    print('没了')

二.死循环语句

     一直循环下去的程序,他会让计算机CPU负载加大,甚至崩溃。

while True:
    print(1)

三.for循环

    for循环相比较while循环语法更加简洁,并且在循环取值更加方便,在编程中用的较为频繁。

name_list = ['zhangsan', 'lisi', 'wangerma', 'wangwu']
for i in name_list:
    print(i)

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

         for循环代码

# for循环字符串
# for i in 'hello world'
# print(i)
# for循环字典:默认只能拿到k
d = {'username': 'jason', 'pwd': 123, 'hobby': 'read'}
for k in d:
    print(k, d[k])

3.1range关键字

# 关键字range
# 第一种:一个参数  从0开始 顾头不顾尾
for i in range(10):
    print(i)
# 第二种:两个参数  自定义起始位置 顾头不顾尾
for i in range(4, 10):
    print(i)
# 第三种:三个参数  第三个数字用来控制等差值
for i in range(2, 100, 10):
    print(i)
# range在不同版本的解释器中 本质不同
#    在python2.X中range会直接生成一个列表
#      在python2.X中有一个xrange也是迭代器
#    在python3.X中range是一个迭代器 节省内存空间
#    '''python2.X中xrange就是python3.x里面的range'''

3.2for+break语句

for i in range(10):
    if i == 4:
        break
    print(i)

3.3for+continue

   continue功能也相当于结束本次循环。

for i in range(10):
    if i == 4:
        continue
    print(i)

3.4for+else循环的嵌套使用

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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM