循环::
for循环是一个结构,导致程序要重复一定的次数。
list1=[1,2,3,4] for i in list1: print i---在序列里,使用for循环遍历。
range() 可以快速的生成一个序列
range(i,j,步进值)
如果所创建的对象为整数,可以用range
列表重写:
print [i*2 for i in range(1,11)] print [i for i in range(1,11) if i%2==0] print [i**2 for i in range(1,11)] for i in [i**2 for i in range(1,11)]: print i
for i in [i**2 for i in range(1,11) if i%2!=0]:
print i
xrange(对象)//返回的是一个对象,对对象进行遍历。
a= xrange(10) for i in a: print i
a= xrange(10) for i in a: print i for i in xrange(100): print i
for 遍历访问字典:
dic1={'a':100,'b':100,'c':100,'d':100,'e':100} # dic1=dic.fromkeys('abcde',100) print dic1 for k in dic1: print k ,dic1[k] for k in dic1: print "%s --->%s" % (k,dic1[k]) for k in dic1: print "%s --->%s" % (k,dic1[k]), print dic1.items() for i in dic1.items(): print i for k,v in dic1.items(): print k,v for k ,v, in dic1.iteritems(): print k,v for i in dic1: print i ,dic1[i] for i in dic1.items(): print i for k,v in dic1.items(): print k,v九九乘法表
for i in xrange(1,10): for j in xrange(1,i+1): print "%s*%s=%s" % (j,i,j*i), print
for
else
for 循环如果正常结束,才会执行else 语句
break
continue
pass //占位
exit()//退出
import time for i in xrange(10): print i time.sleep(1) else: print 'main end'
for i in xrange(10): print i # time.sleep(1) if i == 5: break else: print 'main end'
for i in xrange(10): if i==3: continue elif i==5: continue elif i==6: pass elif i==7: # sys.exit() pass print i else: print 'main end' print "hahaha"
for i in xrange(10): if i==3: continue elif i==5: continue elif i==6: pass elif i==7: sys.exit() # pass print i else: print 'main end' print "hahaha"作业: 猜数字游戏
系统生成一个20以内的随机整数
玩家有6次机会进行猜猜看,每次猜测都有反馈(猜大了,猜小了,猜对了,结束)
六次中,猜对了,玩具赢
否则系统赢了。
随机模块:
random.randint(1,20)
Python 第三方软件:
pip list 查看
for 与while 相比
for 循环用在有次数的循环上
while 循环用在有条件的控制上。
while
while 循环,知道表达式为假,才退出
while循环,表达式是一个逻辑表达式,必须返回一个true或false。
语法:
while expresson:
statement(s)
while是条件循环是如此,当条件变为假,循环结束。
n=0 while True: if n==10: break; print 'hello' n+=1
while True: print 'hello' input=raw_input("please input something,q for quit:") if input=='q': break
while input!='q': print 'hello' input=raw_input("please input something,q for quit:")abs()
x='' while x!='q': print 'hello' x=raw_input("please input something,q for quit:") if x=='': break else: print 'hello world '
x='' while x!='q': print 'hello' x=raw_input("please input something,q for quit:") if x=='': break if x=='quit': continue print 'continue' else: print 'hello world '