7、循环之while循环和深浅copy

一、while循环

1.1、什么是循环结构?

  循环结构就是重复的执行某段代码

1.2、为什么需要循环结构?

  希望计算机能够像人一样具备重复去执行某件事的能力

1.3、怎么使用while循环结构?

1.3.1、循环语法的基本使用:while+else

count=0

while count<3:

  count+=1

else:

  print(count)

1.3.2、死循环与效率问题

while True:

  print(1+1)     #  纯计算无IO会导致致命的效率问题。

1.3.3、退出循环的两种方式

1.3.3.1、将条件改为False,下次循环判断条件时才会生效。while+tag

tag=True

while tag:

  inp_name = input('请输入你的账号:')

  inp_pwd = input('请输入你的密码:')

  if inp_name == ursename and inp_pwd == input:

    print('登陆成功')

    tag=False

  else:

    print('账号或密码错误')

1.3.3.2、break,只要运行到break,就会立即断开本层循环

while True:

  inp_name = input('请输入你的账号:')

  inp_pwd = input('请输入你的密码:')

  if inp_name == ursename and inp_pwd == input:

    print('登陆成功')

    break

  else:

    print('账号或密码错误')

1.3.4、while嵌套循环与结束

1.3.4.1、将条件改成False

username = '123'

password = '321'

tag=True

while tag

  inp_name=input('请输入账号:')

  inp_psd = input('请输入密码:')

  if inp_name == username and inp_psd == password:

    print('登录成功')

    while tag:

      cmd=input('请输入命令:')

      if cmd=='q':

        print('正在登录')

        tag=False

      else:

        print('请输入正确命令:{a}'.format(cmd=a))

  else:

    print('登录失败')

1.3.4.2、用break退出

username = '123'

password = '321'

while 1:

  inp_name=input('请输入账号:')

  inp_psd = input('请输入密码:')

  if inp_name == username and inp_psd == password:

    print('登录成功')

    while :1:

      cmd=input('请输入命令:')

      if cmd=='q':

        print('正在登录')

        break

      else:

        print('请输入正确命令:{a}'.format(cmd=a))

    break

  else:

    print('登录失败')

1.3.5、while+continue:结束本次循环,进入下一次循环

count =0

while count <6:

  if count == 4:

    count +=1  

    continue

  print(count)

  count +=1

1.3.6、案例

要求:允许登录三次,失败则退出,成功要求输入命令,否则继续输入

username = ‘123’

password = '321'

count = 0

while count < 3:

  inp_name = input('请输入你的账号:')

  inp_psd = input('请输入你的密码:')

  if username == inp_name and password == inp_psd:

    print('账号密码正确')

    while 1:

      tag = input('请输入指令:')

      if tag==‘a’:

        print('正在登录中')

        break

      else:

        print('输入的指令{b}错误,请重新输入').format

    break

else:

  print('账号密码错误三次,已关闭')

 

二、深浅copy

在使用程序编写过程中需要将值进行拷贝,更改其中一个变量,另一个变量值不能变化。这就需要深浅copy了。

2.1、赋值

  二者分隔不开,a改b也跟着该,因为指向的就是同一个地址

  a=b

2.2、浅copy列表

a=[1,2,[3,4]]

b=a.copy()

print(id(a[0]),id(a[1]),id(a[2]))

print(id(b[0]),id(b[1]),id(b[2]))

a[0]=5

a[1]=6

a[2][0]=7

a[2][1]=8

print(id(a[0]),id(a[1]),id(a[2]))

print(id(b[0]),id(b[1]),id(b[2]))

如需所示:变化前和变化后的状态

 

 

2.3、深copy列表

a=[1,2,[3,4]]

import copy 

b=copy.deepcopy(a)

print(id(a[0]),id(a[1]),id(a[2]))

print(id(b[0]),id(b[1]),id(b[2]))

a[0]=5

a[1]=6

a[2][0]=7

a[2][1]=8

print(id(a[0]),id(a[1]),id(a[2]))

print(id(b[0]),id(b[1]),id(b[2]))

如图所示:

 

posted @ 2020-03-09 22:50  疏星淡月  阅读(192)  评论(0编辑  收藏  举报