python通过两种方式来实现你的需求:语句和表达式
语句:使用关键字组成命令
>>> print 'Hello wolrd!'
Hello wolrd!
表达式:可以是算术表达式或函数
>>> abs(-4)
4
>>> abs(4)
4
2.1、程序输出,print语句及”hello world”
>>> mystring="hello world"
>>> print mystring
hello world
>>> mystring
'hello world'
注:print语句调用str()函数显示对象,交互式解释器调用repr()函数显示对象。
2.2、程序输入和raw_input()内建函数
>>> _
'hello world'
print语句与字符串格式运算符“%”结合使用,实现字符串替换功能:
>>> print "%s is number %d!" % ("python",1)
python is number 1!
%s表示一个字符串来替换,%d表示一个整数替换,%f表示一个浮点数替换
Print语句支持将输出重定向文件,符号”>>”重定向:
>>> import sys
>>> print >> sys.stderr, 'Fatal error:invalid input!'
Fatal error:invalid input!
[root@localhost tmp]# more log.txt
11111
>>> logfile=open('/tmp/log.txt','a')
>>> print >> logfile,'fatal error:invalid input!'
>>> logfile.close()
[root@localhost tmp]# more log.txt
11111
fatal error:invalid input!
内建函数:raw_input 获取用户数据输入,读取标准输入并赋值给指定变量
>>> user=raw_input('Enter login name:')
Enter login name:root
>>> print 'Your login is:',user
Your login is: root
使用int()内建函数可将用户输入的数值字符串转换为整数:
>>> num=raw_input('Now enter a number:')
Now enter a number:2012
>>> print 'Doubling your number:%d' % (int(num) * 2)
Doubling your number:4024
查看函数帮助信息:help()
>>> help(raw_input)
Help on built-in function raw_input in module __builtin__:
raw_input(...)
(END)
2.3、注释
和shell一样,用”#”标示注释
>>> #one comment
... print 'Hello World!'
Hello World!
DocStrings:文档字符串的惯例是一个多行字符串,它的首行以大写字母开始,句号结尾。第二行是空行,从第三行开始是详细的描述。适用于函数、模块、类。
>>> def foo():
...
...
...
>>> foo()
True
>>> print foo.__doc__
this is a doc string.
>>> help(foo)
Help on function foo in module __main__:
foo()
this is a doc string.
2.4、运算符
算术运算符:+
>>> print -2*4+3**2
1
优先级:**最高,*、/、 //、%、+、-
比较运算符:<
比较运算符结果返回布尔值:True,False
>>> 2<4
True
>>> 2==4
False
>>> 2>4
False
>>> 6.2<=6
False
>>> 6.2<=6.2
True
>>> 6.2<=6.201
True
逻辑运算符:and、or、not
>>> 2<4 and 2==4
False
>>> 2<4 or 2==4
True
>>> not 6.2 <=6
True
>>> 3<4<5
True
>>> 3<4 and 4<5
True
2.5、变量和赋值
变量名由字母、数字、下划线组成,大小写敏感;
变量赋值通过等号”=”执行;
>>> counter=0
>>> miles=1000.0
>>> name='Bob'
>>> counter=counter+1
>>> kilometers=1.609*miles
>>> print '%f miles is the same as %f km' % (miles,kilometers)
1000.000000 miles is the same as 1609.000000 km
>>> n=1
>>> n=n*10
>>> print n
10
>>>
>>> n*=10
>>> print n
100
注:Python不支持c语言的自增、自减运算符,+/-也是单目运算符,--n会解释为-(-n)等于n,++n同上结果为n;
2.6、数字
Python支持5种基本数字类型,三种为整数类型:
Int(有符号整数)
long(长整数)
bool(布尔值)
float(浮点值)
complex(复数)
decimal:十进制数浮点型,非内建类型,需导入模板才可使用
>>> 1.1
1.1000000000000001
>>> import decimal
>>> print decimal.Decimal('1.1')
1.1
2.7、字符串
字符串定义为引号之间的字符合集,支持成对的单引号,双引号,三引号(三个连续的单/双引号)。
使用索引运算符”[ ]”、切片运算符”[ : ]”取得子字符串。字符串索引规则:第一个字符索引是0,最后一个字符串索引是-1。
加号”+”用于字符串连接运算,星号”*”用于字符串重复。
>>> pystr='python'
>>> iscool='is cool!'
>>> pystr[0]
'p'
>>> pystr[2:5]
'tho'
>>> iscool[:2]
'is'
>>> iscool[3:] #第四个到最后
'cool!'
>>> iscool[-1]
'!'
>>> pystr+iscool
'pythonis cool!'
>>> pystr+' '+iscool
'python is cool!'
>>> pystr*2
'pythonpython'
>>> '-'*20
'--------------------'
>>> pystr='''python
... is cool'''
>>> pystr
'pythonnis cool'
>>> print pystr
python
is cool
2.8、列表和元组
可看成数组,能保存任意数量任意类型的python对象,索引也是从0开始。
列表和元组的区别:
列表元素用中括号”[ ]”包裹,元素个数及值可以改变;
元组元素用小括号”( )”包裹,元素不可以更改,可看成只读列表;
都使用索引运算符”[ ]”、切片运算符”[ : ]”取得子集;
列表实例:
>>> list=[1,2,3,4]
>>> list
[1, 2, 3, 4]
>>> list[0]
1
>>> list[2:]
[3, 4]
>>> list[:3]
[1, 2, 3]
>>> list[1]=6
>>> list
[1, 6, 3, 4]
元组实例:
>>> tuple=('robots',77,88,'try')
>>> tuple
('robots', 77, 88, 'try')
>>> tuple[:2]
('robots', 77)
>>> tuple[1]=3
Traceback (most recent call last):
TypeError: object does not support item assignment
2.9、字典
字典是python中的映射数据类型,由键-值(key-value)对构成。几乎所有类型的python对象都可用作键值,数字和字符串最常用。
字典元素用大括号”{ }”包裹。
>>> dict={'host':'earth'}
>>> dict['port']=80
>>> dict
{'host': 'earth', 'port': 80}
>>> dict.keys()
['host', 'port']
>>> dict['host']
'earth'
>>> for key in dict:
...
...
host earth
port 80
2.10、代码块及缩进对齐
python语言是通过缩进对齐表达代码逻辑,不使用大括号,缩进方式可选择tab或空格,这种方式的好处不言而喻,一是简洁美观,二可读性好。
2.11、if语句
if
>>> x=3
>>> if x<5:
...
...
x is 3
if语句支持else、elif于语句:
if
elif expression2:
else:
2.12、while循环,类似if语法
while
>>> counter=0
>>> while counter<3:
...
...
...
loop #0
loop #1
loop #2
2.13、for循环和range()内建函数
>>> for item in ['e-mail','net-surfing','homework','chat']:
...
...
...
net-surfing
homework
chat
print语句通过加入逗号实现添加空格:
>>> who='knights'
>>> what='Ni!'
>>> print 'We are the',who,'who say',what,what,what
We are the knights who say Ni! Ni! Ni!
>>> print 'We are the %s who say %s' %
... (who,((what+' ')*4))
We are the knights who say Ni! Ni! Ni! Ni!
>>> for eachnum in range(3):
...
...
0
1
2
字符串迭代:
>>> foo='abc'
>>> for c in foo:
...
...
a
b
c
range()和len()函数用于字符串索引:
>>> foo='abc'
>>> for i in range(len(foo)):
...
...
a (0)
b (1)
c (2)
enumerate()函数同时循环索引和元素:
>>> for i,ch in enumerate(foo):
...
...
a (0)
b (1)
c (2)
2.14、列表解析
可以在一行中使用一个for循环将所有值放到一个列表当中:
>>> squared=[x ** 2 for x in range(4)]
>>> for i in squared:
...
...
0
1
4
9
2.15、文件和内建函数open()、file()
hand=open(file_name, access_mode=’r’)
file_name变量为打开文件的字符串名字
access_mode中”r”表读取,”w” 表写入,“a”表添加,”+”表读写,”b”表二进制访问,默认为”r”
如果open()成功,一个文件对象句柄会被返回,所有后续的文件操作都必须通过此文件句柄进行。当一个对象返回后,就可以访问它的一些方法,如readlines(),close() . 文件对象的方法属性也必须通过句点属性标识法访问。
属性是与数据有关的项目,属性可以是简单的数据值,也可以是执行对象,如函数和方法。类、模块、文件、复数等对象都拥有属性。通过使用句点属性标识法来访问对象属性:object.attribute
2.16、错误和异常
python程序在运行时可通过try-except语句检测错误,检测到错误后,解释器引发一个异常并显示信息。try后位代码组,except后为处理错误的代码。
>>> filename=''
>>> while 1:
...
...
...
...
...
...
...
...
...
Input a file name:logfile
There is no file named logfile
Input a file name:
There is no file named
Input a file name:/tmp/log.txt
opend a file.
Input a file name:q
2.17、函数
语法:
def function_name([argument])
>>> def addme2me(x):
...
...
...
>>> addme2me(3)
6
>>> addme2me(4.5)
9.0
>>> addme2me('python')
'pythonpython'
>>>
>>>
>>> addme2me([-1,'abc'])
[-1, 'abc', -1, 'abc']
函数参数可以设置默认值,如果调用时没有提供参数,则取默认值:
>>> def foo(debug=True):
...
...
...
...
>>> foo()
in debug mode
done
>>> foo(False)
2.18、类
>>> class fooclass(object):
...
...
...
...
...
...
...
...
...
...
...
...
>>>
>>> fool=fooclass()
create a class instance for John Doe
>>> fool.showver()
0.1
>>> print fool.addme2me(5)
10
>>> print fool.addme2me('xyz')
xyzxyz
2.19、模块
导入模块:import module_name
系统自带很多模块,自己编写的.py结尾的程序也是一个模块,模块名不带后缀,调用模块函数或模块变量通过句点”.”访问。
>>> import sys
>>> sys.stdout.write('Hello World!n')
Hello World!
>>> sys.platform
'linux2'
>>> sys.version
'2.4.3 (#1, Mar
test.py
import.test
2.20、实用的内建函数
dir([obj])
help([obj])
int(obj)
len(obj)
open(fn, mode)
range([[start,]stop[,step]])
raw_input(str)
str(obj)
type(obj)