python for循环n次_Python入门10 —— for循环

1.字符串依次取值

students = ['egon', 'lxx', 'alex']

i = 0

while i < 3:

print(students[i])

i += 1

2.针对循环取值操作,while循环并不擅长,于是python提供一个专门循环取值操作:for循环

students = ['egon', 'lxx', 'alex']

for x in students: # 有几个值就循环几次

print(x)

dic={'name':'egon','age':18,'sex':'male'}

for aaa in dic: # 从字典里取出的默认是key,

print(aaa,dic[aaa])

for x in 'egon':

print(x)

count = 0

while count < 3:

print('======')

print('hello world')

print('======')

count+=1

for x in ['a','b','c']: # x='c'

print('======')

print('hello world')

print('======')

for x in range(3):

print('======')

print('hello world')

print('======')

range(1,3) # 从1开始,顾头不顾尾

for x in range(1,3): # [1,2]

print(x)

range(3):默认从0开始,顾头不顾尾,到2结束,0,1,2

range(1,6) # 可以指定开头,从1开始,顾头不顾尾,到5结束,1 2 3 4 5

range(1,6,2) # 可以指定步长,1 3 5

students = ['egon', 'lxx', 'alex']

for x in students:

print(x)

for i in range(len(students)): # [0,1,2]

print(i)

print(students[i])

# 0 2 4

l=['a','b','c','d','e','f'] #

range(len(l))

for i in range(0,len(l),2):

print(l[i])

3.总结:

一:while循环与for循环

相同之处:

都是循环,都是用来做重复的事情

不同之处

1.while循环通常用来循环执行某段代码

for循环通常用来进行循环取值

2.while循环的循环次数取决于条件什么时候为假

for循环循环的次数取决in后的数据类型所包含的值的个数

二:for+range():range用来产生一个数字序列

用途1:用来重新n次某段代码

用途2:range可以用来产生数字序列,数字对应的是列表的索引

所以说,for+range()是可以按照索引编列列表

for+break

for i in range(3): #

username=input('username>>: ')

password=input('password>>: ')

if username == 'egon' and password == '123':

break

else:

print('用户名或密码错误')

for+continue

for i in range(5): # [0,1,2,3,4]

if i == 2 or i == 3:continue

print(i)

for+else

for i in range(3): #

username=input('username>>: ')

password=input('password>>: ')

if username == 'egon' and password == '123':

break

else:

print('用户名或密码错误')

else:

print('账号密码输错次数达到最大限制,退出程序')

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值