一、字符串

  python中字符被定义为引号之间的字符集合,使用索引操作符([])和切片操作符([:])可以等到子字符串。字符串有其特有的索引规则:第一个字符的索引是0,最后一个字符的索引是-1。

  加号(+)用于字符串连接运算,星号(*)则用于字符串重复。

下面分别举例:

>>> pystr='python'
>>> isool='is cool!'
>>> pystr[0]
'p'
>>> pystr[2:5]
'tho'
>>> isool[:2]
'is'
>>> isool[:1]
'i'
>>> isool[-1]
'!'
>>> isool[-2]
'l'
>>> pystr + isool
'pythonis cool!'
>>> pystr + ' ' + isool
'python is cool!'
>>> pystr * 2
'pythonpython'
>>> '-' * 2
'--'

>>> pystr = '''python
... is cool'''
>>> pystr
'python\nis cool'
>>> print pystr
python
is cool

 

二、列表和元组

  可以将列表和元组当成普通的 “数组”,它能保存任意数量类型的python对象,和数组一样,通过从0开始的数字索引访问元素,但是列表和元组可以存储不同类型的对象。

  列表和元组有几处重要的区别。列表元素用中括号([])包裹,元素的个数及元素的值可以改变。

  元组元素用小括号(())包裹,不可以更改(尽管他们的内容可以)。元组可以看成是只读的列表。通过切片运算([] 和 [:])可以得到子集,这一点与字符串的使用方法一样,当然列表和元组是可以互相转换的。

举例:

>>> alist=[1,2,3,4]
>>> alist
[1, 2, 3, 4]
>>> alist[0]
1
>>> alist[1]
2

>>> alist[1] = 5
>>> alist
[1, 5, 3, 4]
>>> alist[1:3]
[5, 3]

== 元组也可以进行切片运算,得到的结果也是元组(不可更改)

 

>>> atuple = ('a','b','c','d')
>>> atuple
('a', 'b', 'c', 'd')
>>> atuple[:3]
('a', 'b', 'c')
>>> atuple[0:3]
('a', 'b', 'c')
>>> atuple[3]
'd'
>>> atuple[6]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range

      == 元组和列表互转

>>> alist
[1, 5, 3, 4]
>>> atuple
('a', 'b', 'c', 'd')
>>> tuple(alist)
(1, 5, 3, 4)
>>> list(atuple)
['a', 'b', 'c', 'd']

 

三、字典

  字典是python中的映射数据类型,工作原理类似perl中的关联数组或哈希表,由键-值(key-value)对构成。几乎所有类型的python对角都可以用作键,不过一般还是以数字或都字符串最为常用。

  值可以是任意类型的python对象,字典元素用大括号({})包裹。

举例:

>>> adict = {'host':'localhost'}
>>> adict
{'host': 'localhost'}
>>> adict['host']
'localhost'
>>> adict['localhost']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'localhost'
>>> adict['ip']=192.168.1.11
File "<stdin>", line 1
adict['ip']=192.168.1.11
^
SyntaxError: invalid syntax
>>> adict['ip']='192.168.1.11'
>>> adict['ip']
'192.168.1.11'
>>> adict
{'ip': '192.168.1.11', 'host': 'localhost'}
>>> adict['port']=80
>>> adict
{'ip': '192.168.1.11', 'host': 'localhost', 'port': 80}
>>> adict['ipaddress']='192.168.1.11'
>>> adict
{'ip': '192.168.1.11', 'host': 'localhost', 'ipaddress': '192.168.1.11', 'port': 80}

 

四、if语句

  标准if条件语句的语法如下:

  if expression:

    if_suite

  如果表达式的值非0或者为布尔值True,则代码组if_suite被执行;否则就去扫行下一条语句。代码组(suite)是一个python术语,它由一条或多条语句组成,表示一个子代码块。python与其他语言不同,条件表达式并不需要用括号括起来。

  if x < 0:

    print '"x" must be atleast 0!'

  也支持else语句,语法如下。

  if  expression:

    if_suite

  else:

    else_suite

  同样还支持elif语句,如下。 

  if  expression1:

    if_suite

  elif expression2:

    elif_suite

  else:

    else_suite

 

五、while循环

  >>> counter=0 

>>> while counter < 3:
... print 'loop %d' % (counter)
... counter +=1
...
loop 0
loop 1
loop 2

 

六、for循环和range()内建函数

  python中的for循环与传统的for循环(计数器循环)不太一样,它更像shell脚本里的foreach迭代。

python中的for接受可迭代对角(例如序列或迭代器)作为其参数,每次迭代其中一个元素。

 

>>> for item in ['e-mail','net-surfing','homework','chat']:
... print item
...
e-mail
net-surfing
homework
chat

上面例子出输都换行了,因为print语句默认会给每一行添加一个换行符,只要在print语句后面添加一个逗号,就可以改变这种行为。

>>> for item in ['e-mail','net-surfing','homework','chat']:
... print item,
...
e-mail net-surfing homework chat

>>> for i in range(3):
... print i
...
0
1
2

>>> foo = 'abc'
>>> for i in foo:
... print i
...
a
b
c

range()函数经常和len()函数一起用于字符串索引,在这里我们要显示每一个元素及其索引值。

>>> a='cdefg'
>>> a[0]
'c'
>>> a[2]
'e'
>>> for i in range(len(a)):
... print a[i],i
...
c 0
d 1
e 2
f 3
g 4

不过,这些循环有一个约束,你要么循环索引,要么循环元素,这导致了enumerate()函数的推出,它同时做了这两两点。

同样方法如下:

>>> for i,ch in enumerate(a):
... print i,ch
...
0 c
1 d
2 e
3 f
4 g

 

七、列表解析

  这是一个让人欣喜的要术语,表示你可以在一行中使用一个for循环将所有值放到一个列表当中:

>>> a=[x**2 for x in range(3)]
>>> a
[0, 1, 4]

  以及做更复杂的操作

>>> a=[x**2 for x in range(9) if not x % 2]
>>> a
[0, 4, 16, 36, 64]

 

八、文件和内建函数 open(),file()

制作脚本实现输入文件名并读取内容:

[root@CentOS_11 day01]# vim test1.py

import os                      ; 倒入os模块
filename=raw_input('Enter file name:')         ; 交互式输入变量
real=os.path.exists(filename)             ; 判断输出文件是否存在
if real == False:                     ; 如果输入的文件不存在就打印退出
  print "%s is not exist" %filename
  os.sys.exit()
openfile=file(filename,'r')                ; 存在就以只读模式打开此文件
for line in openfile.xreadlines():                   ; 便利每一行并打印           
  print line,
openfile.close()                    ;  关闭文件

 

九、错误和异常

  编译时会检查语法错误,不过python也允许在程序运行时检测错误。当检测到一个错误,python解释器就引发一个异常,

并显示异常的详细信息。程序员可以根据这些信息迅速定位问题并进行调试,并找出处理错误的办法。

  要给你的代码添加错误检测及异常处理,只要将它们“封闭”在try-except语句当中,try之后的

代码组,就是你打算管理的代码。except之后的代码组,则是你处理错误的代码。

  程序员出可以通过使用raise语句故意引发一个异常。

 

十、函数

  类似于其他语言,python中的函数使用小括号(())调用。函数在调用之前必须先定义,

如果函数中没有reture语句,就会自动返回None对角。

  python是通过引用调用的。这意味着函数内对参数的改变会影响到原始对象。不过事实

上只有可变对象会受此影响,对不可变对象来说,它的行为类似按值调用。

 

 posted on 2015-04-13 13:08  阿~贵  阅读(255)  评论(0编辑  收藏  举报