首先申明下,本文为笔者学习《Python学习手册》的笔记,并加入笔者自己的理解和归纳总结。
1. Python语句特点
if
语句中括号()
是可选的。- 冒号
(:)
出现在结尾,表示一个语句的结束。 - 分号
(;)
不用出现在结尾。 - 大括号不再需要,而是以缩进来表示代码块的开始和结尾。
2. if语句
一般格式
if <state1>: # if语句,以分号(:)结尾
<statement1> # 缩进替代大括号
elif <state2>: # elif语句,可以有多个
<statement2>
else: # else语句
<statement3>
只包含if
语句
>>> if x > 1:
print "True"
if
和else
配合使用
>>> if x > 1:
print "True"
else:
print "False"
多路选择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语句
一般格式
while <state1>: # where语句,以分号(:)结尾
<statement1>
else: # else语句,循环正常结束调用
<statement2>
while
单独使用
>>> x = "HelloWorld!"
>>> while x: # x是否是空列表
print x[0],
x = x[1:]
H e l l o W o r l d !
else
是循环结束时调用。
>>> L = [1, 2, 3, 4]
>>> while L:
print L[0],
L = L[1:]
else: # 循环结束,调用else语句
print 6
1 2 3 4 6
4. for语句
一般格式。
for <target> in <object>: # for语句,以分号(:)结尾
<statement1>
else: # else语句,循环正常结束调用
<statement2>
for
单独使用。
>>> for x in [1, 2, 3, 4]:
print x,
1 2 3 4
>>> for x in ("hello", "world"):
print x
hello
world
for
使用元组赋值。
>>> T = [(1, 2), (3, 4), (5, 6)]
>>> for (a, b) in T:
print a, b
1 2
3 4
5 6
>>> for item in T:
a, b = item
print a, b
1 2
3 4
5 6
for
对字典操作时,实际是对字典的关键字列表操作。
>>> D = {"a":1, "b":2, "c":3}
>>> for item in D:
print item, D[item]
a 1
c 3
b 2
else
是循环结束时调用。
>>> L = [1, 2, 3, 4]
>>> for x in L:
print x,
else:
print 6
1 2 3 4 6
5. break和continue语句
break
用来跳出循环。
>>> x = "HelloWorld!"
>>> while True:
if x: # x是否是空列表
print x[0],
x = x[1:]
else: # x是空列表,跳出循环
break
H 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是偶数,跳过下面语句
continue
print x, # 该方法只会打印奇数
1 3 5 7 9
6. pass语句
pass
是空的占位语句。
7. print语句
print
语句用来打印,并在行的末尾添加一个换行。
>>> print "Hello World!" # 打印"Hello World!"并换行
Hello World!
print
在语句中遇到逗号添加一个空格。
>>> print 12, 3.4, "Hello World!"
12 3.4 Hello World!
>>> for x in "123456789":
print x,
1 2 3 4 5 6 7 8 9
print
支持字符串格式化。
以百分号(%)
为格式符,后面是一个元组。具体格式可参见Python字符串格式化。
>>> print "%d" %(12)
12
>>> print "%f, % s" % (3.4, "Hello World!")
3.400000, Hello World!
print
打印重定向。
print
方法使用sys.stdout
的write
方法来实现,可以通过修改sys.stdout
来实现输出的重定向。
>>> import sys # 导入sys模块
>>> tmp = sys.stdout # 变量tmp记录原有的输出目标
>>> sys.stdout = open("log.txt", "w") # 打开一个文件作为新的输出目标
>>> print("Hello World") # 输出内容
>>> print 1, 2, 3
>>> sys.stdout.close() # 关闭文件
>>> sys.stdout = tmp
通过open()
函数读取"log.txt"
文件。
>>> open("log.txt", "r").read()
'Hello World\n1 2 3\n'
也可以查看当前目录,是否存在log.txt
文件。
>>> import os
>>> os.getcwd()
'E:\\'
相关文章
Python 数字类型(一)
Python 布尔型(二)
Python 字符串(三)
Python 列表(四)
Python 字典(五)
Python 元组(六)
Python 集合(七)
Python 变量和作用域(八)
Python 语句(九)
Python 函数(十)
Python 类(十一)
Python 模块(十二)
Python 文档(十三)
Python 文件(十四)
Python 异常(十五)
Python 运算符重载(十六)