1.if语句
Python 中的if子句看起来十分熟悉. 它由三部分组成: 关键字本身, 用于判断结果真假的条件表达式, 以及当表达式为真或者非零时执行的代码块.
if 语句的语法如下:
if expression:
expr_true_suite
if 语句的 expr_true_suite代码块只有在条件表达式的结果的布尔值为真时才执行, 否则将继续执行紧跟在该代码块后面的语句.
(1)多重条件表达式
单个if语句可以通过使用布尔操作符and,or和not实现多重判断条件或是否定判断条件.
if not warn and (system_load >= 10):
print "WARNING: losing resources"
warn += 1
</div>
(2)单一语句的代码块
如果一个复合语句(例如 if 子句, while 或 for 循环)的代码块仅仅包含一行代码, 那么它可以和前面的语句写在同一行上:
if make_hard_copy: send_data_to_printer()
尽管它可能方便, 但这样会使得代码更难阅读, 所以我们推荐将这行代码移到下一行并合理地缩进.
2.else语句
Python提供了与if语句搭配使用的else语句.如果if语句的条件表达式的结果布尔值为假,那么程序将执行else语句后的代码.它的语法你甚至可以猜到:
if expression:
expr_true_suite
else:
expr_false_suite
if passwd == user.passwd:
ret_str = "password accepted"
id = user.id valid = True
else:
ret_str = "invalid password entered... try again!"
valid = False
</div>
3.elif(即else-if)语句
elif是Python的else-if语句,它检查多个表达式是否为真, 并在为真时执行特定代码块中的代码. 和else一样, elif声明是可选的, 然而不同的是: if语句后最多只能有一个else语句, 但可以有任意数量的elif语句.
if expression1:
expr1_true_suite
elif expression2:
expr2_true_suite
elif expressionN:
exprN_true_suite
else:
none_of_the_above_suite
</div>
4.条件表达式(即"三元操作符")
Python 2.5 集成的语法确定为: X if C else Y .
>>> x, y = 4, 3
>>> smaller = x if x < y else y
>>> smaller
3
</div>
5.while语句
Python的while是本章我们遇到的第一个循环语句. 事实它上是一个条件循环语句.与if声明相比,如果if后的条件为真, 就会执行一次相应的代码块. 而while中的代码块会一直循环执行, 直到循环条件不再为真.
while 循环的语法如下:
while expression:
suite_to_repeat
>>> x=1
>>> while x <=100:
print x
x+=10
</div>
6.for语句
Python提供给我们的另一个循环机制就是for语句. 它提供了Python中最强大的循环结构.它可以遍历序列成员, 可以用在列表解析和生成器表达式中,它会自动地调用迭代器的next()方法,捕获StopIteration异常并结束循环(所有这一切都是在内部发生的).和传统语言中的for语句不同, Python的for更像是 shell 或是脚本语言中的foreach循环.
for循环会访问一个可迭代对象(例如序列或是迭代器)中的所有元素, 并在所有条目都处理过后结束循环.它的语法如下:
for iter_var in iterable:
suite_to_repeat
</div>
1.用于序列类型
>>> for c in 'names':
print 'current letter: ', c
current letter: n
current letter: a
current letter: m
current letter: e
current letter: s
</div>
迭代序列有三种基本方法:
1.通过序列项迭代:
>>> namelists = ['henry', 'john', 'steven']
>>> for eachName in namelists:
print eachName, 'Lim'
henry Lim
john Lim
steven Lim
</div>
2.通过序列索引迭代:
>>> namelists = ['henry', 'john', 'steven']
>>> for nameindex in range(len(namelists)):
print 'Liu, ', namelists[nameindex]
Liu, henry
Liu, john
Liu, steven
</div>
3.使用项和索引迭代:
两全其美的办法是使用内建的 enumerate() 函数, 它是 Python 2.3 的新增内容. 代码如下:
>>> namelists = ['henry', 'john', 'steven']
>>> for i, eachLee in enumerate(namelists):
print "%d %s Lee" % (i+1, eachLee)
1 henry Lee
2 john Lee
3 steven Lee
</div>
2.用于迭代器类型
迭代器对象有一个 next() 方法,调用后返回下一个条目. 所有条目迭代完后, 迭代器引发一个 StopIteration 异常告诉程序循环结束. for 语句在内部调用 next() 并捕获异常.
3.range()内建函数
内建函数 range() 可以把类似 foreach 的 for 循环变成你更加熟悉的语句
Python 提供了两种不同的方法来调用range().完整语法要求提供两个或三个整数参数:
range(start, end, step =1)
range() 会返回一个包含所有k的列表,这里start <= k < end ,从start到end, k每次递增step. step不可以为零,否则将发生错误.
>>> range(2, 19, 3)
[2, 5, 8, 11, 14, 17]
</div>
如果只给定两个参数,而省略step,step就使用默认值1.
>>> range(3, 7)
[3, 4, 5

