Python 基本语句

来源:互联网 发布:端口聚合的作用 编辑:程序博客网 时间:2024/06/09 18:30

Python 基本语句

首先申明下,本文为笔者学习《Python学习手册》的笔记,并加入笔者自己的理解和归纳总结。

1、Python语句特点

(1) if语句中括号()是可选的。
(2) 冒号(:)出现在结尾,表示一个语句的结束。
(3) 分号(;)不用出现在结尾。
(4) 大括号不在需要,而是以缩进来表示代码块的开始和结尾。

2、if语句

(1) 一般格式
if <state1>:               # if语句,以分号(:)结尾<statement1>           # 缩进替代大括号elif <state2>:             # elif语句,可以有多个<statement2>else:                      # else语句<statement3>
(2) 只包含if语句。
>>> if x > 1:print "True"
(3) if和else配合使用。
>>> if x > 1:print "True"else:print "False"
(4) 多路选择elif。
>>> if x < -1:print "x < -1"elif x < 0:print "x < 0"elif x < 1:print "x < 1"else:print "x >= 1"

3、while语句

(1) 一般格式。
while <state1>:            # where语句,以分号(:)结尾<statement1>else:                      # else语句,循环正常结束调用<statement2>
(2) while单独使用。
>>> x = "HelloWorld!">>> while x:               # x是否是空列表print x[0],x = x[1:]H e l l o W o r l d !
(3) else是循环结束时调用。
>>> L = [1, 2, 3, 4]>>> while L:print L[0],L = L[1:]else:                      # 循环结束,调用else语句print 61 2 3 4 6

4、for语句

(1) 一般格式。
for <target> in <object>:  # for语句,以分号(:)结尾<statement1>else:                      # else语句,循环正常结束调用<statement2>
(2) for单独使用。
>>> for x in [1, 2, 3, 4]:print x,1 2 3 4>>> for x in ("hello", "world"):print xhelloworld
for使用元组赋值。
>>> T = [(1, 2), (3, 4), (5, 6)]>>> for (a, b) in T:print a, b>>> for item in T:a, b = itemprint a, b1 23 45 6
for对字典操作时,实际是对字典的关键字列表操作。
>>> D = {"a":1, "b":2, "c":3}>>> for item in D:print item, D[item]a 1c 3b 2
(3) else是循环结束时调用。
>>> L = [1, 2, 3, 4]>>> for x in L:print x,else:print 61 2 3 4 6

5、break和continue语句用于循环语句中。

break用来跳出循环。
>>> x = "HelloWorld!">>> while True:if x:                  # x是否是空列表print x[0],x = x[1:]else:                  # x是空列表,跳出循环breakH e l l o W o r l d !
continue用来跳到循环的顶端。
>>> L = [1, 2, 3, 4, 5, 6, 7, 8, 9]>>> for x in L:if x % 2 == 0:         # 如果x是偶数,跳过下面语句continueprint x,               # 该方法只会打印奇数1 3 5 7 9

6、pass语句

pass是空的占位语句。


0 0