Python是一种解释性语言,类似于shell脚本语言,但同时他也可以像java一样按字节编译,生成一种近似于机器语言的中间形式。因此Python也就兼备了解释性语言的易用性和编译语言的高效性。该语言由Guido van Rossum创建于1989年,当时他只花了一个月的时间。当然这也得益于他对解释型语言ABC有着丰富的设计经验。
如何运行python代码
方式1:启动python解释器,例如在linux 的shell下直接运行python命令,即可启动python解释器,然后即可逐条执行python的语句。
[root@pnem-02 ysy]# python
Python 2.4.3 (#1, Dec 10 2010, 17:24:35)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-50)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> mystring="Hello world!"
>>> print mystring
Hello world!
方式2:从命令行启动python脚本
[root@pnem-02 ysy]# cat script.py
#! /usr/bin/python
mystring="Hello world!"
print mystring
[root@pnem-02 ysy]# python script.py
Hello world!
python的输入和输出
python的输入用内建函数raw_input();输出用print语句;输出重定向用“>>”。
>>> name=raw_input('enter your name: ')
enter your name: Jim
>>> age=raw_input('enter your age: ')
enter your age: 24
>>> print "my name is %s, and I'am %d years old." %(name,int(age))
my name is Jim, and I'am 24 years old.
>>> logfile=open('/root/ysy/test.log','a')
>>> print >> logfile,'Test: write a file.'
>>> logfile.close()
>>> logfile=open('/root/ysy/test.log','r')
>>> for eachline in logfile:
... print eachline,
...
Test: write a file.
>>> logfile.close()
python的操作符
a) 算术操作符:
+ - * / % ==》加减乘除求余
// ==》浮点除法
** ==》乘方运算
b) 比较操作符
< <= > >= == != ==》同C语言
<> ==》不等于(ABC/Pascal风格,逐渐在被淘汰)
c) 逻辑操作符
and or not ==》与或非
python支持的数字类型,字符串,以及变量的赋值
a) 五种基本数字类型:
int: 有符号整型
long: 长整型
bool: 布尔值
float: 浮点值
complex: 复数
b) 字符串的定义:
字符串是由引号(可为单、双、三引号)括起来的字符集合。
单双引号最为常见,类似与shell,必须配对使用。特殊字符可以使用转义实现。
三引号可以用来包含python的特殊字符,实际上他就是保持字符串原有格式,例如可以讲字符串写成多行从而避免用转义实现换行。
字符的转义和shell类似,不过python支持用r' '来避免单引号内字符串被转义。
>>> print '\\\t\\'
\ \
>>> print r'\\\t\\'
\\\t\\
>>> print '''line1 ... line2 ... line3''' line1 line2 line3
c) 字符串的操作符:索引操作符“[ ]”;切片操作符“[ : ]”;链接操作符“+”;重复操作符“*”
>>> str1='Python'
>>> str2='is cool'
>>> str1[0]
'P'
>>> str1[1]
'y'
>>> str1[-1]
'n'
>>> str1[-2]
'o'
>>> str1[1:4]
'yth'
>>> str1 + ' ' + str2
'Python is cool'
>>> '*' * 10
'**********'
d) 变量及其赋值和引用
python变量和shell脚本一样不需要预先声明变量类型,变量的类型和值在赋值时被初始化。但是python的变量在引用时更像C语言,不需要项shell脚本那样添加“$”符号。
列表,元组,字典
列表和元组类似于C语言的数组,分别用“[ ]”和“( )”括起来。其中列表的元素个数和值可以改变,元组是不可以的,元组可以视为只读的列表。字典由一个或多个键值对构成,字典元素是键值对,元素间由逗号隔开,整个字典用大括号括起。
<pre class="plain" name="code">>>> list=[1,2,3,4,5]
>>> list[0]
1
>>> list[1:]
[2, 3, 4, 5]
>>> list[4]=0
>>> list
[1, 2, 3, 4, 0]
>>>
>>>
>>> tuple=('a','b','c','d','e')
>>> tuple[0]
'a'
>>> tuple[1:]
('b', 'c', 'd', 'e')
>>> tuple[4]='f'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: object does not support item assignment
>>>
>>>
>>> dict={'sun':7,'mon': 1,'tue':2,'wed':3,'thu':4,'fri':5}
>>> dict
{'wed': 3, 'sun': 7, 'thu': 4, 'tue': 2, 'mon': 1, 'fri': 5}
>>> dict['sat']=6
>>> dict
{'wed': 3, 'sun': 7, 'thu': 4, 'tue': 2, 'mon': 1, 'fri': 5, 'sat': 6}
>>> dict['mon']
1
>>> for key in dict:
... print key,dict[key]
...
wed 3
sun 7
thu 4
tue 2
mon 1
fri 5
sat 6
python的列表是支持“列表解析”的,这也是一个非常有用的功能。
>>> square_evens=[x**2 for x in range(8) if not x%2]
>>> for i in square_evens:
... print i
...
0
4
16
36
python的控制语句:if while for
说到python控制语句,与C语言最大的区别是python不再使用大括号来括起语句块,而是使用缩进对齐的方式来划分语句块。换句话说在python里面必须严格控制语句的缩进。他们的语法分别如下:
a) if语句
if expression1 :
if_suite
elif expression2 :
elif_suite
else:
else_suite
b) while语句
while expression:
while_suite
c) for语句
for item in [a,b,c]:
print item
for语句不同于C语言,只能迭代给定的列表元素。
>>> for item in ['apple','banana','orange']:
... print item,
...
apple banana orange
for语句常与内建函数range()合用来迭代处理一个数字序列。
>>> for num in range(3):
... print num,
...
0 1 2
字符串可以直接放在for循环中迭代其中每一个字符,这一点在字符处理时非常有用,下面的代码便是利用这一特性来统计line中的单词个数的。
>>> cnt=1
>>> line='apple banana orange'
>>> for c in line:
... if c==' ':
... cnt+=1
...
>>> print cnt
3
python的函数
python函数的定义是以关键字def开始,紧接着是函数名,然后是以小括号括起的参数列表,参数之间用逗号隔开。函数调用和C语言类似。
>>> def square(x,note=True):
... if note:
... print 'square of %d :'% (x),
... x*=x
... return(x)
...
>>> square(3)
square of 3 :
9
>>> square(3,0)
9
>>> square(3,False)
9
>>>
需要注意的是,函数的默认参数只能写在非默认参数的后面。如果上面函数square的默认参数note写在x之前,会提示一下错误:
>>> def square(note=True,x):
... if note:
... print 'square of %d :'% (x),
... x*=x
... return(x)
...
SyntaxError: non-default argument follows default argument
python的异常处理
python除了一般的错误信息提示以外,还提供了一种异常处理方式,try-except语句标识。try之后使我们需要管理的代码,except之后是错误处理代码。下面的代码测试了两种情况:一是python的一般错误提示,二是通过try-except封装的自定义错误处理。
>>> filename = raw_input('Enter file name: ')
Enter file name: test.txt
>>> fobj=open(filename,'r')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IOError: [Errno 2] No such file or directory: 'test.txt'
>>> try:
... filename = raw_input('Enter file name: ')
... fobj=open(filename,'r')
... except:
... print 'Error!'
...
Enter file name: text.txt
Error!
python的模块
模块是python的一种组织形式,它实际上就是一个包含代码或者函数或者类的源文件,只是模块名不带.py后缀。一个模块创建之后,可以使用关键字import导入这个模块到你需要的python代码中。例如前文已经使用的sys模块。
>>> import sys
>>> sys.stdout.write('Hello world!\n')
Hello world!
>>> sys.platform
'linux2'
>>> sys.version
'2.4.3 (#1, Dec 10 2010, 17:24:35) \n[GCC 4.1.2 20080704 (Red Hat 4.1.2-50)]'
PS: python还支持面向对象编程,也就是类定义,这里暂时不予介绍。