`
mrjeye
  • 浏览: 176668 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

Python学习笔记

阅读更多
python,怎么说呢,感觉很好玩,以下说明几点笔者感兴趣的东西:
    它抛弃了包裹代码块的花括号,而只依据缩进对代码块进行理解(语句有代码块的要以:结束)
    注释用#,若一行以#开头,则不会被解释
   
    FOR循环的用法不同,Python的FOR和java中的for in功能一样,具体可以参照后续代码
    for语法:
    for iter in iter:
    ...
    else:    #当且仅当在FOR循环结束时没遇到BREAK标签时执行
    ...

    对象的比较有些时髦:
    >>> 2>1<3
    True        #相当于:(2>1) and (1<3)
    >>> 2>1<0
    False
   
    这是一条正确的赋值方法:i=j=1    #i=1;j=1
   
    列表:x=[1,2,3]        #值可变,EG:x[0]=4
    元组:x=(1,2,3)        #值不可变
    字典:dict={'name':'tom','age':18}    #可改值,EG:dict['age']=20
        迭代:首先调用 dict.keys() 得到‘键’,然后用for in依次取值
        EG:
            >>>dict={1:1,2:2}    #其键与值理论上来说允许为任何对象
            >>>keys = dict.keys()
            >>>for k in keys:
            ...    print('key is :%s,value is :%s' % (k,dict[k]))

    字符串倒有些没见过的语法
    >>> str='this is a test .'    #声明一个对象(字符串,字符串两边可用单引或双引号)
    >>> str[5:-1]            #返回(会直接打印)STR中从第5个索引位到最后的子字符串(索引从0开始,最后一个位置索引为-1,不含最后一个位置的值)
    'is a test '           
    >>> str[:4]            #返回字符串从开始位置到第4个索引位置的子字符串
    'this'
    >>> str*2            #重复两次字符串(传说+、-、*、/等运算符可用于很多对象)
    'this is a test .this is a test .'
    >>> str[6]            #取第6个索引位置的字符
    's'

    原始字符串:引号前加 r 标识的字符串为一个原始字符串,其不对\转义

    声明字符串时可用三引号,用以允许一个字符串跨多行的情况
    >>> responseTxt = '''<html>
    ...     <head>
    ...             <title>test</title>
    ...     </head>
    ...     <body>
    ...             Hello
    ...     </body>
    ... </html>'''
    >>> print responseTxt
    <html>
        <head>
            <title>test</title>
        </head>
        <body>
            Hello
        </body>
    </html>
    >>> responseTxt
    '\n<html>\n\t<head>\n\t\t<title>test</title>\n\t</head>\n\t<body>\n\t\tHello\n\t
    </body>\n</html>'

    可以这样声明一个字符串:s='Hello'' ''Python'
    >>> 'Hello'' ''Python'
    'Hello Python'

    #string.capitalize()    把字符串第一个字符转换成大写

    #string.center(len)    将string居中,两头用空格填充
    >>> 'abc'.center(16)
    '      abc       '

    #string.count(str[,begin[,end]])    #返回str在string中出现的次数
    >>> s='abcdada'
    >>> s.count('a')
    3
   
    >>> s='abcdada'
    >>> s.zfill(10)
    '000abcdada'

    迭代字符串中的字符用enumerate
    >>> for idx,ch in enumerate('abc'):    #可以理解成函数enumerate返回一个元组
    ...     print('idx :%d,ch :%s' %(idx,ch))
    ...
    idx :0,ch :a
    idx :1,ch :b
    idx :2,ch :c
   
    #元组类型的参数转换
    >>> dict = {'a':'1','b':'2'}
    >>> print 'The %(a)r and %(b)s' %dict
    The '1' and 2
   
    #字符串之Template
    >>> from string import Template
    >>> t = Template('the value of key \'id\' is ${id}')
    >>> t.substitute(id=5)
    "the value of key 'id' is 5"

    变量名不能以$开始、不推荐使用__作为变量的开始
    列表解析是个好玩意(可能只是好奇吧- -;),可以筛选出一些元组
   
    OO时:
    构造方法名字特别:
        >>>def __init__(self):
        ...    ...
    在类中的所有需要供外部访问的方法第一个参数都是指向调用者的 self 引用
        ...
        >>>def add(self,i,j):
        ...    return i+j
    关于OO,据说不是PYTHON的重点(至少笔者看的这本书上讲得不多),但本人非常喜欢


    关于运行代码:
        你可以打开python的IDLE或使用python命令(WINDOWS下)打开它的控制台
        然后直接输入命令交互执行,或这样:python c:\Python26\cat.py 指定一个PY文件
        其它系统笔者还没了解过,以后会接触到
        (关于什么安装配置,这里就不说了)

    导入模块,import module_name、from moudle_name import Object

===================================================================================
简单的入门知识

玩玩FOR语句
>>> def jfor(begin,end,step):
...     flag = 0
...     for i in range(end-begin+1):
...             if flag ==0:
...                     print i+begin
...                     flag=step-1
...             else:
...                     flag-=1
...

FOR 中的 enumerate
>>> for i,ch in enumerate('abc'):
...     print '%d is %s' %(i,ch)
...

列表解析--筛选
>>> r = [x for x in range(10) if x%2<>1 if x!=0]
>>> r
[2, 4, 6, 8]

文件操作
1---

>>> def f():
...     fileName = raw_input('Type file name :')
...     for eachLine in file(fileName,'r'):    #模式可选read/write/append...
...             print eachLine,
...
>>> f()
Type file name :c:\1.log
this is a test .
haha

2---

>>> def f():
...     fileName = raw_input('Type file name :')
...     try:
...             for eachLine in file(fileName,'r'):
...                     print eachLine,
...     except IOError,e:
...             print 'open/read file error :%s' %(e)
...
>>> f()
Type file name :c:\nofile
open/read file error :[Errno 2] No such file or directory: 'c:\\nofile'
>>> f()
Type file name :c:\1.log
this is a test .
haha

OO
class Cat(object):
    name=''        #stact property
    def __init__(self,name):
        print "init the cat (%s)." %(name)
        self.__class__.__name__=name
    def setName(self,name):
        self.__class__.__name__=name
    def getName(self):
        return self.__class__.__name__

此猫的实例对NAME都引用同一个地址

再来一个Cat
class Cat(object):
    __name = ''    #private property
    __age =0
    def __init__(self,name,age):
        self.__name = name
        self.__age = age
        print 'init cat , name is %s;age is %d' %(name,age)
    def getName(self):
        return self.__name
    def getAge(self):
        return self.__age
    def setName(self,name):
        self.__name = name
    def setAge(self,age):
        self.__age = age

此猫的实例对NAME、AGE的引用是私有的
(没有看到OO那去,这只是猜想,如果有问题,请赐教- -;)
-----------------------------------------------------------
用OO来个实例
模拟DOS界面操作,启动程序用户选择相应功能操作:

class Main(object):
    'the main class .'
    def __init__(self):
        self.showMenu()        #go to main menu
    def showMenu(self):
        selectItem = int(raw_input('Select the function (1-add two num ; 2--say some worlds ; 0--exit):'));
        while(selectItem!=0):        #loop until user type '0'
            if selectItem == 1:
                no = NumOper()    #just play
                first = int(raw_input('Type the first number :'))
                secrend = int(raw_input('Type the secrend number :'))
                print '%d+%d=%d' %(first,secrend,no.add(first,secrend))
                del no
            elif selectItem == 2:
                str = raw_input("Type yout name :");
                print 'Hello %s , Welcome to back !' %(str)
            else:
                print 'you choose item (%d) is invalid .' %(selectItem)
            selectItem = int(raw_input('Select the function (1-add two num ; 2--say some worlds ; 0--exit):'));
        print 'bye ~~'
        exit()
#just play
class NumOper(object):
    'the number oper .'
    def add(self,fir,sec):
        return fir+sec


对象的属性可以这样访问:
>>> import cat
>>> c=cat.Cat('cat',18)
init cat , name is cat;age is 18
>>> c
<cat.Cat object at 0x00BA3810>
>>> id(c)
12204048
>>> dir(c)
['_Cat__age', '_Cat__name', '__class__', '__delattr__', '__dict__', '__doc__', '
__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__'
, '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str
__', '__subclasshook__', '__weakref__', 'getAge', 'getName', 'setAge', 'setName'
]
>>> c._Cat__age    #访问属性
18
===================================================================================
第三章节那些东西

变量
在python中,不用显示地声明变量,也不用给变量指定类型,一切的事都将在变量第一次被赋值是自动声明

赋值语句可以这样:i,j,k=(1,2,3)    #当然可以不要括号
交换变量的值:x,y=y,x
    甚至可以这样做:x,y,z=y,z,x

如果模块是导入的,在里面 __name__ 会被设置成模块的名字;否则如果模块是直接执行的 __name__ 会被设置成 __main__
这样的话,可以在每一个模块写入相应的测试代码,在测试代码入口(顶层代码)判断是否是直接执行的,若是则执行相应测试代码;反之不管

经典的异常语句
try:
    ...
except IOError,e:    #估计python会把错误信息放在变量e里面
    ...
else:
    ...        #这里执行的条件是:TRY块没有发生异常

关于os模块
    判断一个文件是否存在: os.path.exists(__file)
    得到当前系统的分行符:os.linesep

字符串函数
    >>> s='abc'+'''
    ...
    ... '''
    >>> s
    'abc\n\n'
    >>> s.strip()
    'abc'
1
2
分享到:
评论

相关推荐

    Python学习笔记(干货) 中文PDF完整版.pdf

    这份"Python学习笔记"涵盖了从环境搭建到基础语法,再到数据类型和控制结构等关键知识点,旨在为初学者提供全面的学习指导。 首先,1.1章节介绍了Python的基础,包括Python的起源和历史。Python是由Guido van ...

    Python学习笔记--皮大庆.pdf.zip

    【Python学习笔记--皮大庆.pdf.zip】是一个针对初学者的Python编程教程,源自英文书籍《How to think like a computer scientist》。这本书以易懂的方式介绍了Python语言的基础知识,旨在帮助没有编程背景的人快速...

    python学习笔记.pdf

    在这份《python学习笔记.pdf》中,记录了Python编程的基础知识和一些技巧,内容涵盖了字符串处理、变量操作、数据结构、循环、条件判断等方面。以下是对学习笔记中提到知识点的详细说明。 ### 字符串处理 在Python...

    Python学习笔记-王纯业

    【Python学习笔记-王纯业】是一份专为Python初学者设计的教程,由王纯业编撰。这个教程深入浅出地介绍了Python编程的基础知识,帮助初学者快速上手。下面将详细阐述该教程中可能包含的重要知识点,以及Python入门者...

    王纯业的Python学习笔记

    《王纯业的Python学习笔记》是一份专为Python初学者和进阶者设计的学习资料,旨在帮助读者全面掌握这门强大的编程语言。Python作为一门高级编程语言,因其简洁、易读的语法特性,被广泛应用于数据分析、机器学习、...

Global site tag (gtag.js) - Google Analytics