for循环使用的语法: for 变量 in 序列: 循环要执行的动作
1)range( ) range( )是python中产生一个数的集合工具,基本结构为range(start,stop,step),即产生从start数开始,以step为步长,至stop数结束的数字集合,不包含stop数,start可以省略,默认为0,step也可,默认值为1
range序列的用法:
range(1,10) ###不取尾数,表示1-9### range(1,11,2) ###1-11的奇数### range(2,10,2) ###2-10的偶数### 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():结束程序的运行 for循环练习: 题目: 有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) 题目: 用户登陆程序需求:
输入用户名和密码;
判断用户名和密码是否正确? (name=‘root’, passwd=‘westos’)
登陆仅有三次机会, 如果超>过三次机会, 报错提示; 模拟命令行:
import os for i in range(1000): cmd = input('[kiosk@python test]$ ') if cmd: if cmd == 'exit': print('logout') else: print('run %s' %cmd) os.system(cmd) else: continue