python之条件和循环
上一篇 / 下一篇 2013-10-20 18:57:30 / 个人分类:python
#if语句
#1、组成,关键字本身 + 真假条件 + 执行代码块
a = 100
b = 120
if a < b:
print "a < b"
#2、多重条件表达式:可以通过使用布尔操作符and / or 和not 实现多重判断条件或是否定判断条件
warn = 10
if not warn and (b >= 100):
print "QARNING:losing resources"
warn += 1
#else 语句
if password == user.password:
ret_str = "password accept"
id = user.id
valid = True
else:
ret_str = "invalid password entered ... try again!"
valid = False
#elif语句
if user.cmd == "create":
action = "create item"
elif user.cmd == "delete":
action = "delete item"
elif user.cmd == "update":
action = "update item"
else:
action = "invalid choice ... try again"
#上面的语句可以简化为下面:
if user.cmd in ("create","delete","update"):
action = "%s item"%(user.cmd)
else:
action = "invalid choice ... try again"
#另一种方式
msgs = {"delete":"delete item","create":"create item","update":"update item"}
default = "invalid choice ... try again"
action = msgs.get(user.cmd,default)
#条件表达式(三元操作符),类似java 、c 的 c ? x : y 结构的,语法为y if c else y.
x, y = 4 ,3
smal = x if x < y else y #如果x < y ,smal = x, 如果 x>y,smal = y
#while语句
count = 0
while(count < 9):
print "the index is :",count
count += 1
#for循环
#用于序列类型
#迭代字符串
for eachLetter in "zhaoyehong":
print "current letter:",eachLetter
#通过序列项list
nameList = ["wahter","Micle","Steven","Henry"]
for eachName in nameList:
print eachName
#通过序列索引来迭代
for eachIndex in range(len(nameList)):
print nameList[eachIndex]
#通过项和索引来进行迭代
for i,eachname in enumerate(nameList):
print "%d %s"%(i,eachname)
#range()函数:range(start,end,step = 1):返回一个包含k 的列表, start =< k < end,每次都会递增step个,step 不能为0,否则会有异常.range(start,end),range(end)
#range()函数不能只传入end 和step参数,会被认为是start和end参数
print range(2,19,3) #输出为[2,5,8,11,14,17]
print range(2,5) #输出[2,3,4] 不包含最后end的数
print range(4) #输出[0,1,2,3]
for eachVal in range(2,19,4):
print "value is :",eachVal
#与序列相关的内建函数sorted()zip(),这两个函数返回一个序列,reversed() enumerate(),这两个返回一个迭代器,类似序列
albums = ("pop","Gaudi","Freud","Poe2")
year = (1976,1987,1990,2003)
for album in sorted(albums):
print album,
for album in reversed(albums):
print album,
for i,album in enumerate(albums):
print l,album
for album,yr in zip(albums,year):
print yr,album #1976 pop 1987 Gaudi ....
#break语句:当某个条件被触发,立即重循环中退出。用于while和for循环
count = num /2
while count > 2:
if num % count == 0:
print "is the largest factor of ",num
break
count -= 1
phone2remove = "555-33"
for eachPhone in phoneList:
if phone2remove == eachPhone:
print "found",phone2remove ,"is deleted"
deleteFromPhoneDB(phone2remove)
break
#continue:程序终止此次循环,并忽略剩余语句,回到循环的顶端,开始下一次迭代器啊,如果是条件循环,将先验证条件表达式。如果是迭代循环,将先元组是否还有元素可以迭代。只有验证成功,才能进入下一次迭代
#continue用于while条件循环和for迭代循环
valid = False
count = 3
while count > 0:
input = raw_input("enter password:")
for eachPasword in passwordList:
if input == eachPasword:
valid = True
break
if not valid:
print "invalid input:"
count -= 1
continue
else:
break
#pass语句:它不做任何事情,标记你后来要完成的代码
def foo_func():
pass
#else的另一种用法:在while和for循环中使用else,其中放入只在循环完成后执行的代码。也就是退出循环后马上执行的代码
#for循环中if条件一直不满足,则最后就执行else语句
#循环语句后可以有一个else从句,这个else从句在因为for循环中list全部遍历完或者因为while循环中条件不满足而执行,而如果循环中有break语句执行了则else从句就不执行了。
#最后一句话概括该else何时可以执行:当for /while循环中不满足其内部代码定义的逻辑时,该else就会被执行
#例如下面例子;寻找一个数的最大约数:
def showMaxFactor(num):
count = num /2
while count > 0:
if num % count == 0:
print "found,largest factor of %d is %d"%(num,count)
break
count -= 1
else:
print num,"is prime"
for eachNum in range(10,21):
showMaxFactor(eachNum)
#迭代器和iter()函数
#迭代器:就是有一个next()方法的对象。不是通过索引来计数的。当想获取下一个数时,调用next()方法就可以获取它
#使用迭代器,迭代序列
myTuple = (123,'xyz',45.56)
i = iter(myTuple)
print i.next() #输出123
print i.next() #输出xyz
print i.next() #输出45.56
print i.next() #抛出异常,越界了。所以最好放在一个try except中
myTuple = (123,'xyz',45.56)
feach = iter(myTuple)
while True:
try:
i = feach.next()
except StopIteration:
break
print i
#使用迭代器,迭代字典:还有三个迭代函数:legends.iterkeys() .itervalues() .iteritems()
legends = {('poe','author'):(1809,1849,1976),('Gaudi','architect'):(1852,1903,1987)}
for eachLegend in legends:
print "name%s Occupation: %s"%eachLegend
print 'Brith: %s Death :%s album: %s'%legends[eachLegend]
#使用迭代器,迭代文件:文件对象生成的迭代器会自动调用readline()方法,循环就可以访问文本文件的所有行
#如下面所示,可以使用myFile替换myFile,readLines()
myfile = open("g://a.txt")
for eachLine in myfile.readLines():
print eachLine
for eachLine in myfile:
print eachLine
#注意:不能再迭代可变对象的时候修改它们,会抛出异常
#如何创建迭代器iter(obj):它会首先检查是不是传入的序列,如果是,会根据索引从0开始到序列介绍。如果是创建传入参数是类,则必须实现__iter__(),next()连个方法
#iter(func,sentinel):会重复调用func,知道迭代器的下个值为sentinel
#列表解析:list comprehension,用来动态创建列表 语法:[expr for iter_var in iterable]:迭代iterable的所有条目,expr是对每个iter_var都要应用的表达式。在编写的时候不要忘记[]
map(lambda x:x**2,range(6))
#等价于
print [x**2 for x in range(6)] #0 1 4 9 16 25 ,需要用[]括起来,不然会报错误,因为元组是不能够更改的,不能用()
#还有一个语法:[expr for iter_var in iterable if cond_expr] :会过滤cond_expr条件
def odd(n):return n %2
seq = (1,2,3,4,556,7,7,8,53)
filter(lambda x:x%2,seq)
#等价于
[x for x in seq if x %2]
#多个迭代
[(x+1,y+2) for x in range(3) for y in range(5)]
#统计一个文件有多深个非空白符的数目
f = open('g://a.txt')
print len( [word for line in f for word in line.split()] )
f.seek(0)
print sum( [len(word) for line in f for word in line.split()] )
#生成器表达式:与列表解析非常相似,而且他们的基本语法基本相同,只是他不是真正地创建数字列表,而是返回一个生成器。这个生成器在每次计算出来一个条目后,把这个条目“产生”yied出来。
#列表解析:[expr for iter_var in iterbable if cond_expr]
#生成器表达式:(expr for iter_var in iterbable if cond_expr),只是把[]换成 了(),生成器并没有使列表解析废弃,只是一个内存使用更友好的结构。使用 了‘延迟计算’。所以它相对于列表解析来说更方便
#如上面计算单词总共的长度
print sum(len(word) for line in f for word in line.split())
#交叉配对样例:结果有点像笛卡尔积
row = [1,2,3]
def cols():
yield 56
yield 3
yield 1
print ((i,j) for i in row for j in cols()) #(1, 56)(1, 3)(1, 1)(2, 56)(2, 3)(2, 1)(3, 56)(3, 3)(3, 1)
#一下是计算一个文件内的寻找文件最长行的例子进化:
#1
f = open("e://a.txt")
longest = 0
while True:
linelen = len(f.readline.strip())
if not linelen:break
if linelen > longest:
longest = linelen
f.close()
print longest
#2
f = open("e://a.txt")
longest =0
alllines = f.readlines()
f.close()
for line in alllines:
linelen = len(line.strip())
if linelen > longest:
longest = linelen
print longest
#3
f = open("e://a.txt")
alllines = [len(x.strip) for x in f]
f.close()
print max(alllines)
#4
f = open("e://a.txt")
longest = max(len(x,strip()) for x in f)
f.close()
print longest
TAG: