循环和数据的操作命令

         while循环的本质就是让计算机在满足某一条件的前提下去重复做同一件事情(即while循环为条件循环,包含:1.条件计数循环,2条件无限循环)

1.1计数循环

count=0

while (count < 9):

print('the loop is %s' %count)

count+=1 

1.2无限循环

count=0

while True:

print('the loop is %s' %count)

count+=1

1.3while与break,continue,else连用

 

count=0
while (count < 9):
    count+=1
    if count == 3:
        print('跳出本层循环,即彻底终结这一个/层while循环')
        break
    print('the loop is %s' %count)

 

break跳出本层循环

 

    count=0

while (count < 9):

count+=1
    if count == 3:

print('跳出本次循环,即这一次循环continue之后的代码不再执行,进入下一次循环')

continue
    print('the loop is %s' %count)

 

count=0

while (count < 9):

count+=1
    if count == 3:

print('跳出本次循环,即这一次循环continue之后的代码不再执行,进入下一次循环')

continue
    print('the loop is %s' %count)

else:

print('循环不被break打断,即正常结束,就会执行else后代码块')

1.4条件为真就重复执行代码,直到条件不再为真,而if是条件为真,只执行一次代码就结束了

  • while有计数循环和无限循环两种,无限循环可以用于某一服务的主程序一直处于等待被连接的状态
  • break代表跳出本层循环,continue代表跳出本次循环
  • while循环在没有被break打断的情况下结束,会执行else后代码

 

 

import getpass

 

account_dict={'alex':'123','eric':'456','rain':'789'}
count = 0
while count < 3:
    name=input('用户名: ').strip()
    passwd=getpass.getpass('密码: ')
    if name in account_dict:
        real_pass=account_dict.get(name)
        if passwd == real_pass:
            print('登陆成功')
            break
        else:
            print('密码输入错误')
            count+=1
            continue
    else:
        print('用户不存在')
        count+=1
        continue
else:
    print('尝试次数达到3次,请稍后重试')

 

用户登陆验证

 

 

for循环

2.1for 循环提供了python中最强大的循环结构(for循环是一种迭代循环机制,而while循环是条件循环,迭代即重复相同的逻辑操作,每次操作都是基于上一次的结果,而进行的)

 

 遍历序列类型

复制代码
name_list=['alex','eric','rain','xxx']

#通过序列项迭代
for i in name_list:
    print(i)

#通过序列索引迭代
for i in range(len(name_list)):
    print('index is %s,name is %s' %(i,name_list[i]))

#基于enumerate的项和索引
for i,name in enumerate(name_list,2):
    print('index is %s,name is %s' %(i,name)) 
复制代码

 

2.2range()语法:

range(start,end,step=1):顾头不顾尾

  • range(10):默认step=1,start=0,生成可迭代对象,包含[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

 2.3for循环为迭代循环

  • 可遍历序列成员(字符串,列表,元组)
  • 可遍历任何可迭代对象(字典,文件等)
  • 可以用在列表解析和生成器表达式中
  • break,continue,else在for中用法与while中一致
 

albums = ('Poe', 'Gaudi', 'Freud', 'Poe2')
years = (1976, 1987, 1990, 2003)

#sorted:排序
for album in sorted(albums):
    print(album)

#reversed:翻转
for album in reversed(albums):
    print(album)

#enumerate:返回项和
for i in enumerate(albums):
    print(i)
#zip:组合
for i in zip(albums,years):
    print(i)

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

    

 

posted @ 2017-07-20 20:03  韩晓飞  阅读(183)  评论(0编辑  收藏  举报