版权声明:https://blog.csdn.net/weixin_42499593 https://blog.csdn.net/weixin_42499593/article/details/89196184
1.语句语法
for循环使用的语法:
for 变量 in 序列:
循环要执行的动作
1)range( )
range( )是python中产生一个数的集合工具,基本结构为range(start,stop,step),即产生从start数开始,以step为步长,至stop数结束的数字集合,不包含stop数,start可以省略,默认为0,step也可,默认值为1
range(stop): 0 - stop-1
range(start,stop): start - stop-1
range(start,stop,step): start - stop-1 step(步长)
2)for循环使用的语法
break:跳出整个循环,不会再循环后面的内容
continue:跳出本次循环,continue后面的代码不再执行,但是循环依然继续
exit():结束程序的运行
2.for循环练习
1)
题目:
有1,2,3,4四个数字
求这四个数字能生成多少互不相同且无重复数字的三位数(122,133)
count = 0
for i in range(1,5):
for j in range(1,5):
for k in range(1,5):
if i != j and j !=k and i != k:
print(i * 100 + j * 10 + k)
count += 1
print('生成%d个无重复的三位数' %count)
2)
题目:
用户登陆程序需求:
1. 输入用户名和密码;
2. 判断用户名和密码是否正确? (name=‘root’, passwd=‘westos’)
3. 登陆仅有三次机会, 如果超>过三次机会, 报错提示;
trycount = 0
while trycount < 3:
name = input('用户名: ')
password = input('密码: ')
if name == 'root' and password == 'westos':
print('登录成功')
break
else:
print('登录失败')
print('您还剩余%d次机会' %(2-trycount))
trycount += 1
else:
print('登录次数超过3次,请稍后再试!')