本文旨在对Python作一个快速的介绍,这样就可以根据之前已有的编程经验识别语言结构,并立刻使用Python
1.程序输出
用print来显示变量的内容
>>>myString = 'hello world'
>>>print myString
hello world
在交互式环境中也可以
>>>myString
'hello world'
较之上有引号是因为输出的是对象的字符串表示,而不仅仅是字符串本身
下划线"_"在解释器有特别含义,表示最后一个表达式的值
>>>_
hello world
print与格式操作符"%"结合可实现字符串替换功能
>>>print "%s is the most %s language" % ("Python", "popular")
Python is the most popular language
%s 字符串替换 %d 整型替换 %f 浮点替换
print支持重定向文件
输出重定向到标准错误输出
import sys
print >> sys.stderr, 'Fatal error: invalid input!'
输出重定向到文件
logfile = open('/tmp/mylog.txt', 'a')
print >> logfile, 'Fatal error: invalid input!'
logfile.close()
2.程序输入
使用raw_input()内建函数从用户得到输入数据
>>>num = raw_input('input a number: ')
input a number: 1000
>>>print 'half your number: %d' % (int(num)/2)
half your number: 500
num得到字符串数据,int()转换为int整型数据
3.注释
从#号开始,至行尾为注释
>>>print 'hello world' #one comment
hello world
文档字符串的特殊注释,在模块,类,函数的起始添加字符串,起在线文档的作用
def foo():
"This is a doc string"
return True
可用于在线生成文档
4.操作符
算术运算符
+ - * / // % **
加减乘除不解释
/与//都为除法,/执行地板除,取比商小的最大整数;//执行浮点除法,是真正的除法
%取余
**为乘方运算符
优先级 + - <* / // % < **
比较运算符
< <= > >= == !=|<>
根据表达式的值返回布尔值
逻辑操作符
and or not
可将表达式连接一起,并得到布尔值
5.变量与赋值
变量名大小写敏感,由字母开头,其他字符可以是数字、字母和下划线组成的标识符
不需要预先声明类型,类型和值在赋值的时候初始化
>>>count = 0
>>>miles = 100.0
>>>name = 'Allen'
>>>count = count +1
>>>kilometers = miles * 102.4
6.数字
五种基本的数字类型
int long bool float complex
decimal算作第六种类型,需要导入decimal模块
decimal,用于十进制浮点型,可以精确表示浮点数
7.字符串
字符串定义为引号之间的字符集合
Python支持使用成对的单引号,双引号,三引号包含字符;使用索引操作符([ ])和切片操作符([ : ])可以得到子字符串,第一个字符索引为0,最后一个为-1
(+)用于字符串转接,(*)用于字符串重复
>>>iscool = 'is cool'
>>>iscool[2:5]
' co'
>>>iscool[1:]
's cool'
>>>iscool * 2
is coolis cool
>>>'-' * 20
'--------------------'
8.列表和元组
列表和元组可被当成普通的“数组”,能保存任意类型的Python对象
列表用([ ])包含,个数及元素可改变
元组用(( ))包含,不可改变,可看作只读的列表
通过索引([ ])和切片([ : ])可得到子集,与字符串操作类似
>>>myList = [1, 2, 3, 4]
>>>myList
[1, 2, 3, 4]
>>>myList[2:]
[3, 4]
>>>myTuple = {'robber', 77, 32.2, 'try'}
>>>myTuple[:2]
{'robber', 77}
9.字典
字典是Python的映射数据类型,由键-值(key-value)对构成
所有Python类型都可作为键和值
字典元素用({ })包含
>>>myDict = {'host', 'earth'} #create dict
>>>myDict['port'] = 80 #add to dict
>>>myDict
['host' : 'earth', 'port' : 80]
>>>myDict.keys()
['host', 'port']
>>>myDict['host']
'earth'
>>>for key in myDict:
print key, myDict[key]
host earth
port 80
10.代码块及缩进对齐
代码块通过缩进表达代码逻辑,而不是大括号
如果你实在讨厌使用缩进作为代码分界,半年之后再来看这种方式,也许你会发现生活中没有大括号并不会像你想像的那么糟糕
11.if 语句
有三种基本形式
>>>myDict = {'host', 'earth'} #create dict
>>>myDict['port'] = 80 #add to dict
>>>myDict
['host' : 'earth', 'port' : 80]
>>>myDict.keys()
['host', 'port']
>>>myDict['host']
'earth'
>>>for key in myDict:
print key, myDict[key]
host earth
port 80
如果表达式的值为非0或布尔值True,if_suite被执行,否则执行下一条语句
12.while 循环
while expression:
while_suite
循环直到expression变成0或False
>>>count = 0
>>>while count < 3:
... print 'loop #%d' % (count)
... count += 1
loop #0
loop #1
loop #2
13.for 循环和range()内建函数
for循环和传统的不同,更像foreach迭代
>>>count = 0
>>>while count < 3:
... print 'loop #%d' % (count)
... count += 1
loop #0
loop #1
loop #2
如果想输出在一行而不是每个元素换行,while_suite可以修改为"print item,"(即加上,号)
结果如
e-mail net home chat (带,的print输出元素会自动添加空格)
例如
>>>count = 0
>>>while count < 3:
... print 'loop #%d' % (count)
... count += 1
loop #0
loop #1
loop #2
类似传统的计数迭代,Python提供range()函数来生成这种列表,即
for eachNum in range(3)
对字符串,很容易迭代每一个字符
>>>foo = 'abc'
>>>for c in foo:
... print c
...
a
b
c
结合range()和len()可以用于字符串索引
>>>foo = 'abc'
>>>for i in range(len(foo)):
... print foo[i], '(%d)' % i
...
a (0)
b (1)
c (2)
Python新增enumerate()函数同时遍历索引和元素
>>>for i, ch in enumerate(foo):
... print ch, '(%d)' % i
...
a (0)
b (1)
c (2)
14.列表解析
表示可以在一行用一个for循环将所有值放入一个列表中
>>>squared = [x ** 2 for x in range(4)]
>>>for i in squared:
... print i
...
0
1
4
9
甚至更复杂的事情
>>>sqdEvens = [x ** 2 for x in range(4) if not x % 2]
>>>for i in sqdEvens:
... print i
...
0
4
15.文件
打开文件
handle = open(file_name, access_mode = 'r')
file_name 打开的文件名称
access_mode 打开文件的模式 'r'读 'w'写 'a'添加 '+'读写 'b'二进制访问 默认为'r'
filename = raw_input('enter file name:')
fobj = open(filename, 'r')
for eachline in fobj:
print eachline
fobj.close()
16.错误与异常
try-except语句
try:
filename = raw_input('enter file name:')
fobj = open(filename, 'r')
for eachline in fobj:
print eachline
fobj.close()
except IOError, e:
print 'file open error:', e
17.函数
函数通过()调用,调用之前必须定义,如果没有return语句,返回None对象
Python通过引用调用,函数内对参数的改变会影响到原始对象
def function_name([arguments]): #参数可选,且可以有默认参数
"optional documentation string" #注释
function_suite #语句
def addMe2Me(x = 3):
'apply + operation to argument'
return (x + x)
18.类
定义类
class ClassName(base_class[es]): #继承的基类,如果没有则可以使用object作为基类
"optional documention string"
static_member_declarations #成员定义
method_declarations #函数定义
class FooClass(object):
"""my first class"""
version = 1.0
def __init__(self, name = 'david'): #__init__()构造器,self为自身的引用,如同c++的this
"""construction"""
self.name = name
print 'create a class instance for', name
def showname(self):
"""display instance attribute and class name"""
print 'your name is', self.name
print 'my name is', self.__class__.__name__
>>>foo1 = FooClass()
create a class instance for david
>>>foo2 = FooClass('Jane')
create a class instance for Jane
>>>foo2.showname()
your name is Jane
my name is FooClass
19.模块
模块是一种组织形式,将彼此有关系的Python代码组织到一个个独立文件中,模块的名字是不带.py后缀的文件名
导入模块
import module_name
访问模块内容
module.function()
module.variable
>>>import sys
>>>sys.platform
'win32'
>>>sys.stdout.write('hello world\n')
hello world
20.部分实用函数
dir([obj])
#显示对象属性,无参数则显示全局变量的名字
help([obj])
#文档帮助
int(obj)
#强制类型转换int
len(obj)
#对象的长度
range([start,]stop[,step])
#返回整形链表
str(obj)
#强制类型转换string
type(obj)
#返回对象类型,返回值为一个type对象