5、while循环与for循环

一、引子

  1、什么是循环?

  循环就是重复做某件事

  2、为何要有循环

  为了控制计算机能够像人一样去重复做某件事

  3、如何用循环

  基本语法:

  while 条件:

    代码1

    代码2

    代码3

二、while循环的基本用法

  例:

  i=0

  tag=True

  while tag:

    if  i==5

      tag=false

    print(i)

    i+=1

 

  i=0

  while i<6

    print(i)

    i+=1

三、死循环:条件永远为True

  例如:1+1

  CPU如果参与计算的循环,将会占用CPU的性能,造成伤害

四、结束while循环的两种方式

  方式一:把条件改为False

  特点:等到本次循环体代码运行完毕后,下一次循环判断条件时才会生效

  例如:

i = 0
tag = True
while tag:
    if i == 5 :
        tag = False
        print(i)
        i+=1

  

  方式二、break代表结束本层循环

  特点:立即干掉本层的while循环

  

i = 0
tag =     True
while tag
    if i == 5:
        tag = False
        print(i)
        i+=1

四、嵌套多层的while循环

  方式一:

tag = True
while tag:
    while tag:
        while tag:
            tag = false

  方式二:

  

while True:
     while True:
         while True:
             break
         break
     break

五、案例

  

 
username = 'egon' password = '123' tag = True while tag <= 3: inp_name = input('请输入您的账号:') inp_pwd = input('请输入您的密码:') if inp_name == username and inp_pwd == password: print('登录成功') while True: print(""" 0 退出 1 存款 2 取款 3 转账 """) count = input("请选择您的业务") if count == "0": break elif count == "1": print('正在存款中。。。') elif count == "2": print('正在取款中。。。') elif count == "3": print('正在转账中。。。') print('谢谢您的使用,再见') else: print('账号名或密码错误') tag += 1 if tag == 4: print("你没了")

六、while+continue

  结束本次循环,直接进入下次

count = 0
while count < 6:
    if count == 2 or count == 4:
        # break
        count += 1
        continue  # continue同级别之后千万别写代码,写了也不会运行
    print(count)
    count += 1

七、while+else:的子代码块会在while循环正常死亡时运行,没被break干掉的叫正常死亡

count = 0
while count < 5:
    if count == 2:
        # count += 1
        # continue
        break
    print(count)
    count += 1
else:
    print('====>')

八、for循环

  1、基本用法:

  

for x in names:
    print(x)

dic={"k1":111,'K2':2222,"k3":333}
for x in dic:
    print(x,dic[x])

for x in "hello":
    print(x)

for x,y in [["name","egon"],["age",18],["gender","male"]]:  # x,y = ['name', 'egon']
    print(x,y)

  2、for+break

  

for i in [11,22,33,44,55]:
    if i == 33:
        break
    print(i)

  3、for+continue

 

for i in [11,22,33,44,55]:
    if i == 33:
        continue
    print(i)

  4、for+else

for i in [11,22,33,44,55]:
    if i == 33:
        break
    print(i)
else:
    print('++++++++>')

  5、range

i=0
while i < 3:
    print(111)
    print(222)
    print(333)
    i+=1


for x in range(3):
    print(111)
    print(222)
    print(333)

 

 

 

 

posted @ 2020-12-21 16:47  BaiM0  阅读(288)  评论(0)    收藏  举报