[python] 初步学习

由于突然提前要来公司实习,这边桌上有一本python,就先学学python吧....

本来最近想写cgi,和用lamp 写php,搞 web开发的..........ORG

很不情愿的,半推半就的开始学习python.

第一本书 python核编程 .

安装python 2.7.3 win32bit

安装pythonwin 开发环境

安装notepad++ 添加 cmd /k python "$(FULL_CURRENT_PATH)"  & PAUSE & EXIT 宏


第一章 ,python的特点....蛮好.俺就是喜欢perl

第二章.快速入门

2.1 程序输出

  print 'hello world;

  print (也有printf 的功能)

print "%s is number %s" % ("PERL" ,1)


import sys

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

重定向

log = open(‘/tmp/mylog.txt’,'a')

print >>logfile,'Fatal error ::invalid input'

log.close()


想法和疑问,print  是否在末尾补回车

      print  后面是否可以用.号连接字符串

                       open的错误捕获以及选项

      如何获取文件句柄的文件描述符

      定义变量如果和函数或者关键重名,如何限制?如 open ='hehe'   print open  感觉怪怪,难免会有存在歧义的地方,智能理解上下文

2.2程序输入和raw_input

user = raw_input('Enter login name:')

类似于 print 'Enterlogin name:' use =<>; chomp;(perl)

输入内容放入user, 自动去掉换行

挺好

2.3注释

# one  comment

2.5 操作符

+  -  * /(整除) //( 浮点除法)  % **

 <   <=   >   >=  ==   !=  <> 避免用后者 两个都是不等号

and  or  not  与或非

2.5变量和赋值

略 counter = 0

2.6 数字

2.7 字符串

类似string 又类似matlab的下标

 a='hello'           a[0:3]  输出  hel

2.8列表和元组

列表用[] ,像字符串一样访问   

元组 是只读 列表 ,用()

2.9字典

 adict  = {'host':'earth'}

  adict.keys()       adict.values()  返回列表

2.10 代码缩紧

2..11 -2.13

if  xxxx:

  ifstatement


for sth  in  列表或元组字典文件句柄: # 字典则sth取key  句柄就是逐行读取

  body


while xxx:

         body


range(5) 相当于 perl中的 0..4

疑问:循环的continue 和 break

2.14  列表解析

a = [ x**2 for x in range(8) if x % 2]  可以把for  if 加入列表生成的用法


2.15 open file

open(filename, ' 方式')  可以有 r,w ,a 添加    + 读写   b 二进制

2.16错误和异常

try:

except sth, e:

                   body

2.17  函数

def function_name([argument])

"document "

  function_suite

                return sth  或者return


#中途练习,写一个快速排序

def qsort(a,begin,end):
    #this is qsort
    print "begin: %d \t end %d\t" % (begin,end)
    if begin < end :
        r = partition(a,begin,end)
        qsort(a,begin, r -1)
        qsort(a,r+1, end)
        
def partition(a,p,q):
    #this is partiton
    key = a[p]
    i = p+1 
    for j  in range( p+1,q ) :
        if a[j] < key :
            if j!=i :
                a[i],a[j] = a[j] ,a[i]
            i = i + 1
    a[i-1],a[p] = a[p],a[i-1]
    return i-1

a= [2,4,23,5,44,1,90]
print a
qsort(a,0,len(a)-1)
print a


遇到到两个问题...for循环和C++不一样,交换也不同

暂时不太明白,python是传值还是传引用,有的文章说,大部分时候引用,小部分时候传值

               C++swap (int &a,int &b)  tmp = a; a = b ; b= tmp              而python,

 w  = [1,2]

def  swap(a,b):

         tmp = a

          a =b

         b= tmp

swap(w[0],w[1])

没能交换,网上查到一篇文章 http://blog.csdn.net/ccat/article/details/8349  好像是说在局部命名空间交换了,但是全局没交换...

 目前的方法是,a,b = b,a 

-----------------------分割线------------------------------------------------------------------

2.18 Classes

  class ClassName (base_class[es]):
     "optional documentation string"
     static_member_declarations
     method_declarations
class FooClass(object):
    """my very first class: FooClass"""
    version = 0.1           # class (data) attribute
    def __init__(self, nm='John Doe'):
        """constructor"""
        self.name = nm      # class instance (data) attribute
        print'Created 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  # references FooClass.version
    def addMe2Me(self, x):     # does not use 'self'
        """apply + operation to argument"""
        return x + x

foo1 = FooClass("rio")
print foo1.showname()
print foo1.showver()
print foo1.addMe2Me('mike')

私有公有如何区分,虚拟多态如何实现

2.19 module

import module_name  
一点疑问,模块里的函数导出,是否有像perl exporter的机制


2.20useful function

Table 2.1. Useful Built-In Functions for New Python Programmers

Function

Description

dir([obj])

Display attributes of object or the names of global variables if no parameter given

help([obj])

Display object's documentation string in a pretty-printed format or enters interactive help if no parameter given

int(obj)

Convert object to an integer

len(obj)

Return length of object

open(fn, mode)

Open file fn with mode ('r' = read, 'w' = write)

range([[start, ]stop[,step])

Return a list of integers that begin at start up to but not including stop in increments of step; start defaults to 0, and step defaults to 1

raw_input(str)

Wait for text input from the user, optional prompt string can be provided

str(obj)

Convert object to a string

type(obj)

Return type of object (a type object itself!)


posted @ 2012-12-20 18:02  程序员杰诺斯  阅读(130)  评论(0编辑  收藏  举报