1、if语句
1、多重条件表达式
单个 if 语句可以通过使用布尔操作符 and , or 和 not
if not warn and (system_load >= 10): print "WARNING: losing resources"
2、单一语句代码块
如果一个复合语句(例如 if 子句, while 或 for 循环)的代码块仅仅包含一行代码, 那么它可 以和前面的语句写在同一行上:
if make_hard_copy: send_data_to_printer()
2、else语句
if expression: expr_true_suite else: expr_false_suite
1、避免“悬挂 else”
if (hi>1) if (hi>7) printf("好棒好棒!") else printf("切~")
在这个例子中,虽然else想与外层if匹配,但是按照C语言的语法,这个else是属于内层if的。初学者的一不小心,就容易导致bug出现,这就是“悬挂else”。
python有强制的缩进规定,能够明确表示出else是属于哪一个if的,从而避免出现“悬挂else”的情况发生。
3、elif语句
if expression1: expr1_true_suite elif expression2: expr2_true_suite elif expressionN: exprN_true_suite else: none_of_the_above_suite
4、条件表达式,三元表达式
a = 30 b = 50 c = 80 max = a if (a > b and a> c) else (b if b>c else c ) print(max)
三元表达式的嵌套
a if a>b else c if c>d else d
5、while语句
1、一般用法
while expression: suite_to_repeat
2、计数循环
count = 0 while (count < 9): print 'the index is:', count count += 1
3、无限循环
while True: handle, indata = wait_for_client_connect() outdata = process_request(indata) ack_result_to_client(handle, outdata)
6、for语句
1、一般用法
for 循环会访问一个可迭代对象(例如序列或是迭代器)中的所有元素, 并在所有条目都处理过 后结束循环
for iter_var in iterable: suite_to_repeat
2、用于序列类型
涵盖字符串, 列表, 以及元组.
迭代序列有三种基本方法:
序列项迭代:
>>> nameList = ['Walter', "Nicole", 'Steven', 'Henry'] >>> for eachName in nameList: ... print eachName, "Lim"
序列索引迭代:
>>> nameList = ['Cathy', "Terry", 'Joe', 'Heather', 'Lucy'] >>> for nameIndex in range(len(nameList)): ... print "Liu,", nameList[nameIndex]
序列项和索引迭代:
>>> nameList = ['Donn', 'Shirley', 'Ben', 'Janice', ... 'David', 'Yen', 'Wendy'] >>> for i, eachLee in enumerate(nameList): ... print "%d %s Lee" % (i+1, eachLee)
3、用于迭代器类型
用 for 循环访问迭代器和访问序列的方法差不多. 唯一的区别就是 for 语句会为你做一些额 外的事情. 迭代器并不代表循环条目的集合.
迭代器对象有一个 next() 方法, 调用后返回下一个条目. 所有条目迭代完后, 迭代器引发一 个 StopIteration 异常告诉程序循环结束. for 语句在内部调用 next() 并捕获异常.
4、range()内建函数
完整语法要求提供两个或三个整数参数:
range(start=0, end, step =1)
class range(object): """ range(stop) -> range object range(start, stop[, step]) -> range object Return an object that produces a sequence of integers from start (inclusive) to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, ..., j-1. start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3. These are exactly the valid indices for a list of 4 elements. When step is given, it specifies the increment (or decrement). """ def count(self, value): # real signature unknown; restored from __doc__ """ rangeobject.count(value) -> integer -- return number of occurrences of value """ return 0 def index(self, value): # real signature unknown; restored from __doc__ """ rangeobject.index(value) -> integer -- return index of value. Raise ValueError if the value is not present. """ return 0 def __bool__(self, *args, **kwargs): # real signature unknown """ self != 0 """ pass def __contains__(self, *args, **kwargs): # real signature unknown """ Return key in self. """ pass def __eq__(self, *args, **kwargs): # real signature unknown """ Return self==value. """ pass def __getattribute__(self, *args, **kwargs): # real signature unknown """ Return getattr(self, name). """ pass def __getitem__(self, *args, **kwargs): # real signature unknown """ Return self[key]. """ pass def __ge__(self, *args, **kwargs): # real signature unknown """ Return self>=value. """ pass def __gt__(self, *args, **kwargs): # real signature unknown """ Return self>value. """ pass def __hash__(self, *args, **kwargs): # real signature unknown """ Return hash(self). """ pass def __init__(self, stop): # real signature unknown; restored from __doc__ pass def __iter__(self, *args, **kwargs): # real signature unknown """ Implement iter(self). """ pass def __len__(self, *args, **kwargs): # real signature unknown """ Return len(self). """ pass def __le__(self, *args, **kwargs): # real signature unknown """ Return self<=value. """ pass def __lt__(self, *args, **kwargs): # real signature unknown """ Return self<value. """ pass @staticmethod # known case of __new__ def __new__(*args, **kwargs): # real signature unknown """ Create and return a new object. See help(type) for accurate signature. """ pass def __ne__(self, *args, **kwargs): # real signature unknown """ Return self!=value. """ pass def __reduce__(self, *args, **kwargs): # real signature unknown pass def __repr__(self, *args, **kwargs): # real signature unknown """ Return repr(self). """ pass def __reversed__(self, *args, **kwargs): # real signature unknown """ Return a reverse iterator. """ pass start = property(lambda self: object(), lambda self, v: None, lambda self: None) # default step = property(lambda self: object(), lambda self, v: None, lambda self: None) # default stop = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
5、 与序列相关的内建函数
sorted(), reversed(), enumerate(), zip()
7、break语句
以结束当前循环然后跳转到下条语句
8、continue语句
continue语句结束本次循环,并回到该循环语句的开头,根据条件判断是否继续执行该循环语句(结束当前循环)
9、pass语句
起到一个过度的作用,
10、再谈else语句
while 和 for 循环中使用 else 语句
如果while和for循环中一直不满足,则会执行else语句。