条件和条件语句
- 下面的值在作为布尔表达式的时候,会被解释器看作假(False):
False None 0 "" () [] {} - 条件执行和if语句
name = raw_input('What is your name?\n') if name.endswith('Gumby'): print 'Hello, Gumby' else: print 'I donot know you!'
- elif 字句
num = input("PLS input a num\n") if num > 0: print "The num is positive!" elif num < 0: print "The num is negetive!" else: print "The num is zero"
结果:
PLS input a num 0 The num is zero
更复杂的条件
- 比较预算符
== ; < ; > ; >= ; <= ; != ; is ; is not ; in ; not in - 相等运算符
>>> 'foo' == 'foo' True >>> 'foo' == 'fo' False
- is:同一性运算符
>>> x = y = [1,2,3] >>> z = [1,2,3] >>> x == y True >>> x == z True >>> x is y True >>> x is z False >>> id(x) 19018656 >>> id(y) 19018656 >>> id(z) 11149144
同一性可以理解为内存地址相同的数据。
- in:成员资格运算符
>>> name = ['a','b','c'] >>> 'a' in name True
- 字符串和序列比较
字符串可以按照字母顺序排列进行比较。>>> 'beat'>'alpha' True
程序会遍历比较
>>> 'Forst'.lower() == 'F'.lower False >>> 'Forst'.lower() == 'Forst'.lower() True
- 布尔运算符
略过 - 断言
如果需要确保程序中的某个条件一定为真才能让程序正常工作的话,assert 语句就有用了,它可以在程序中置入检查点,条件后可以添加字符串,来解释断言:>>> age = -1 >>> assert 0<age<100, 'the age must be crazy' Traceback (most recent call last): File "<pyshell#7>", line 1, in <module> assert 0<age<100, 'the age must be crazy' AssertionError: the age must be crazy
循环
- while
它可以用来在任何条件为真的情况下重复执行一个代码块name = '' while not name: name = raw_input("input your name:\n") print "hello ,%s!" %name
运行结果:
input your name: world hello ,world!
- for循环
>>> for number in range(101): print number
- 迭代工具
①并行迭代>>> names = ['anne','beth','george'] >>> ages = [1,11,111] >>> zip(names,ages) [('anne', 1), ('beth', 11), ('george', 111)] >>> for name, age in zip(names,ages): print name, 'is',age anne is 1 beth is 11 george is 111
② 编号迭代
enumerate函数
③ 翻转和排序迭代
>>> sorted('hello,world!') ['!', ',', 'd', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w'] >>> list(reversed('hello,world!')) ['!', 'd', 'l', 'r', 'o', 'w', ',', 'o', 'l', 'l', 'e', 'h']
- 跳出循环
① break
结束(跳出)循环可以使用break语句>>> from math import sqrt >>> for n in range(99,0,-1): root = sqrt(n) if root == int(root): print n break 81
② continue
③ while True/break 习语
while True: word = raw_input("PLS input a word:") if not word:break print 'the word is:%s'%word