欢迎访问www.showerlee.com, 您的支持就是我前进的动力.

[PYTHON] 核心编程笔记之二-Python起步

showerlee 2013-11-22 21:59 Programming, PYTHON 阅读 (5,380) 抢沙发

最近一直在学习python,所以把自己平时总结的笔记贴出来,供大家分享

2.1 程序输入,print语句及"Hello World"

例:取绝对值

>>>abs(-4)

4

>>>abs(4)

4

例:print输出

>>>myString = 'Hello World!'

>>>print myString

Hello World!

>>>myString

'Hello World!'

注: print语句调用str()函数显示对象,而交互式解释器则调用repr()函数显示对象

2.2 程序输入和内建函数raw_input()

例:程序输入

>>>print "%s is number %d!" %("python",1)

Python is number 1!

注:$s表示由一个字符串来替换,而%d由一个整数来替换,%f表示由一个浮点数来替换

例:将输出重定向到标准错误输出

>>>import sys

>>>print >> sys.stderr, 'Fatal error: invalid input!'

Fatal error: invalid input!

例:将输出重定向到日志文件

>>> logfile = open('~/python/log.txt','a')

>>> print >> logfile, 'fuck you!'

>>> logfile.close()

# cat ~/python/log.txt

Fatal error: invalid input!

例:获取用户输入raw_input()

>>> user = raw_input('Enter login name: ')

Enter login name: root

>>> print 'Your login name is: ',user

Your login name is:  root

例:输入一个数值字符串,并转换成整数

>>> num = raw_input('Now enter a number: ')

Now enter a number: 1024

>>> print 'Doubling your number: %d' % (int(num)*2)

Doubling your number: 2048

注:从交互式解释器中获取帮助

>>> help(raw_input)

2.3 注释

>>> # one comment

... print 'Hello World!'# another comment

特别注释

------------------

def foo()

"This is a doc string."

return True

------------------

2.4 运算符

+-*///(对结果四舍五入)

%(返回除法的余数)**(幂)

>>> print -2*4+3**2

1

<<=>>===!=<>

>>> 2 < 4

True

>>>6.2 <= 6.2.0001

True

andornot

>>>2 < 4 and 2 == 4

False

>>> 2 >4 or 2 < 4

True

>>> 3 < 4 < 5

True

注:合理使用括号增强代码可读性

2.5 变量和赋值

Python大小写敏感,为动态类型语言,不需要预先声明变量

>>> counter = 0

>>> name = "Bob"

n = n*10 可以写成 n* = 10

2.6 数字

int (有符号整数)

long (长整数)

bool (布尔值)

float (浮点值)

complex (复数)

例子:

int 0101 82 -234 0x80 -2312 -0x92

long 432423423L -4324234 0xDWADAWFFAWDAWD

bool True False

float 3.1415926 -90.2 7.2435e2

complex 6.23+1.5j -1.23-423432J

利用isinstance()函数,来判断一个对象是否是一个已知的类型:

>>>lst = []

>>>isinstance(lst, list)

True

>>>isinstance(lst, (int, str, list))

True

2.7 字符串

加号 + 用于字符串连接,星号 * 用于字符串重复

>>>pystr = 'Python'

>>>iscool = 'is cool!'

>>>pystr[0]

'P'

>>>pystr[2:5]

'tho'

>>> iscool[:2]

'is'

>>> iscool[3:]

'cool'

>>> iscool[-1]

'!'

>>>pystr + ' ' + iscool

'Python is cool!'

>>>pystr * 2

'PythonPython'

2.8 列表和元祖

列表和元祖=普通的数组,可存储不同类型的对象

列表用[]包裹,元素个数和值可以改变

元祖用()包裹,可看成是只读列表

>>> aList = [1,2,3,4]

>>> aList

[1, 2, 3, 4]

>>> aList[0]

1

>>> aList[2:]

[3, 4]

>>> aList[:3]

[1, 2, 3]

>>> aList[1] = 5

>>> aList

[1, 5, 3, 4]

元祖可进行切边运算,得到的结果也是元祖(不可修改)

>>> aTuple = ('robots',77,93,'try')

>>> aTuple

('robots', 77, 93, 'try')

>>> aTuple[:3]

('robots', 77, 93)

>>> aTuple[1] = 5

Traceback (most recent call last):

 File "<stdin>", line 1, in <module>

TypeError: 'tuple' object does not support item assignment

2.9 字典

字典是Python中映射数据类型,由键-值(key-value)对构成,所有类型的对象都可以用作键值,一般以数字和字符串作为键值

字典元素用{}包裹

>>> aDict = {'host':'earth'} # create dict

>>> aDict['port'] = 80 # add to dict        

>>> aDict

{'host': 'earth', 'port': 80}

>>> aDict.keys() # key

['host', 'port']

>>> aDict['host'] # value

'earth'

>>> for key in aDict: # 遍历key,value

...   print key,aDict[key]

...

host earth

port 80

2.10 代码块及缩进对齐

Python通过缩进对齐表达代码逻辑,而不使用大括号

2.11 if语句

if expression:

if_suite

如果表达式的值非0或布尔值为True,则代码组if_suite被执行,否则执行下一条语句

else语句:

if expression:

if_suite

else:

else_suite

elif语句:

if expression1:

if_suite

elif expression2:

elif_suite

else:

else_suite

2.12 while循环

while expression:

while_suite

语句while_suite会被连续不断的循环执行,直到表达式值变为0或False: Python才会执行下一句代码

>>> counter = 0      

>>> while counter < 3:

...   print 'loop #%d' %(counter)

...   counter += 1

...

loop #0

loop #1

loop #2

2.13 for循环和range()内建函数

Python中的for接受可迭代对象作为其参数,每次迭代其中一个元素

>>> print 'I like to use the Internet for: '

I like to use the Internet for:

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

...   print item

...

e-mail

net-surfing

homework

chat

在print语句后面添加一个逗号(,),就可以让输出在同一行显示

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

...   print item,

...

e-mail net-surfing homework chat

带逗号的print语句输出的元素间会自动添加一个空格

>>> who = 'knights'

>>> what = 'Ni!'

>>> print 'We are the',who, 'who say',what,what,what,what

We are the knights who say Ni! 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 [0,1,2]:

...    print eachNum

...

0

1

2

利用range()内建函数来生成列表,实现递增计数

>>> for eachNum in range(3):

...   print eachNum

...

0

1

2

迭代每一个字符

>>> 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)

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

>>> for i,ch in enumerate(foo):

...   print ch, '(%d)' %i

...

a (0)

b (1)

c (2)

2.13 列表解析

表示在一行中使用一个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(8) if not x %2]

>>> for i in sqdEvens:

...   print i

...

0

4

16

36

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

打开文件:

handle = open(file_name,access_mode = 'r')

file_name变量为打开文件的字符串名字

access_mode中'r'表示读取,'w'表示写入,'a'表示添加.'+'表示读写,'b'表示二进制访问,如果未提供 access_mode, 默认值 'r'.

如果open()成功,一个文件对象句柄会被返回,所有后续文件操作都必须通过此文件句柄进行,当一个文件对象返回之后,我们就可以访问它的一些方法,比如readlines()和close().文件对象的方法属性也必须通过句点属性标示法访问

注: 什么是属性?

属性是与数据有关的项目,属性可以是简单的数据值,也可以是可执行对象,比如函数和方法,那些对象拥有属性呢?很多,类,模块,文件还有复数等等对象都拥有属性.

访问对象属性,使用句点属性标示法,也就是在对象名和属性名之间加一个句点:

object.attribute

例:输入文件名,然后打开一个文件,并显示它的内容到屏幕上:

----------------------------

#!/usr/bin/env python

filename = raw_input("Enter file name: ")

fobj = open(filename,'r')

for eachLine in fobj:

 print eachLine,

fobj.close()

-----------------------------

2.16 错误和异常

添加错误检测及异常处理 只要将它们封装到try-except语句中,try下的代码组就是你打算管理的代码,except之后的代码,就是你处理错误的代码

#!/usr/bin/env python

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

2.17 函数

Python中函数使用小括号()调用,调用前必须先定义,函数中木有return语句,就会自动返回None对象

>>> def addMe2Me(x):

...     'apply + operation to argument'

...     return (x + x)

...

# 调用函数

>>> addMe2Me(4.25)

8.5

>>> addMe2Me(10)

20

>>> addMe2Me('Python')

'PythonPython'

>>> addMe2Me([-1,'abc'])

[-1, 'abc', -1, 'abc']

默认参数

表示参数调用时如果木有提供这个参数,就会取这个值作为默认值

>>> def foo(debug = True):                              

...   'determine if in debug mode with default argument'

...   if debug:                                        

...     print 'in debug mode'                          

...   print 'done'

...

>>> foo()                                              

in debug mode

done

>>> foo(False)

done

注:debug参数有一个默认值True,如果木有传参,debug会自动拿到True值,返回函数内的结果,如果传一个参数False,默认参数就木有使用

2.18 类

面向对象编程,扮演相关数据及容器的角色

定义类

class ClassName(base_class[es])

"optional documentation string"

---------------------------------------

#!/usr/bin/env python

class FooClass(object):

 '''my very first class: FooClass'''

 version = 0.1 # 定义静态变量

 def __init__(self,nm='John Doe'): # 自定义一个__init__方法

   '''constructor'''

   self.name = nm

   print 'Createed a class instance for',nm

 def showname(self): # 定义一个方法,并对自身引用

   '''display instance attribute and class name'''

   print 'Your name is', self.name

   print 'My name is', self.__class__.__name__

 def showver(self):

   '''display class(static) attribute'''

   print self.version

 def addMe2Me(self,x):

   '''apply + operation to argument'''

   return x + x

# 调用__int__()方法

fool = FooClass()

# 调用showname()方法

fool.showname()

fool.showver()

print fool.addMe2Me(5)

print fool.addMe2Me('xyz')

--------------------------------------------

# python test.py

------------------

# 调用__int__()的返回结果

Createed a class instance for John Doe

# 返回showname()方法结果

Your name is John Doe

My name is FooClass

0.1

10

xyzxyz

------------------

2.19 模块

模块将彼此有关系的代码组织到一个独立文件中

当你创建了一个Python源文件,模块的名字就是不带 .py后缀的文件名,一个模块创建之后,可以从另一个模块中使用import 语句导入这个模块来使用

例:

>>> import sys

# write()不会自动在字符串后面添加换行符号

>>> sys.stdout.write('Hello World!\n')

Hello World!

>>> sys.platform

'linux2'

>>> sys.version

'2.7.3 (default, Sep 26 2012, 21:51:14) \n[GCC 4.7.2]'

2.20 实用的函数

函数描述

dir([obj])显示对象的属性,如果没有提供参数,则显示全局变量的名称

help([obj])以一种整齐美观的形式 显示对象的文档字符串,如果没有提供参数,则会进入交互式帮助  

int(obj)将一个对象转换为整数

len(obj)返回对象的长度

open(fn,mode)以mode('r' = 读, 'w'=写)方式打开一个文件名为fn的文件

range([[start,]stop[,step])返回一个整数列表,起始值为 start,结束值为stop - 1;start默认值为0,step默认值为1

raw_input(str)等待用户输入一个字符串,可以提供一个可选的参数str用作提示信息

str(obj)将一个对象转换为字符串

type(obj)返回对象的类型(返回值本身是一个type对象!)  

正文部分到此结束
版权声明:除非注明,本文由(showerlee)原创,转载请保留文章出处!
本文链接:http://www.showerlee.com/archives/980

继续浏览:PYTHON

还没有评论,快来抢沙发!

发表评论

icon_wink.gif icon_neutral.gif icon_mad.gif icon_twisted.gif icon_smile.gif icon_eek.gif icon_sad.gif icon_rolleyes.gif icon_razz.gif icon_redface.gif icon_surprised.gif icon_mrgreen.gif icon_lol.gif icon_idea.gif icon_biggrin.gif icon_evil.gif icon_cry.gif icon_cool.gif icon_arrow.gif icon_confused.gif icon_question.gif icon_exclaim.gif